C++ int to string, concatenate strings [duplicate]

2019-03-02 09:52发布

This question already has an answer here:

I'm new to C++ and working on a simple project. Basically where I'm encountering a problem is creating a file with a number (int) in the file name. As I see it,I have to first convert the int to a string (or char array) and then concatenate this new string with the rest of the file name.

Here is my code so far that fails to compile:

int n; //int to include in filename
char buffer [33];
itoa(n, buffer, 10);
string nStr = string(buffer);

ofstream resultsFile;
resultsFile.open(string("File - ") + nStr + string(".txt"));

This gives a couple compilation errors (compiling in Linux):

  1. itoa not declared in this scope
  2. no matching function for call to ‘std::basic_ofstream char, std::char_traits char ::open(std::basic_string char, std::char_traits char , std::allocator char )’

I've tried the advice here: c string and int concatenation and here: Easiest way to convert int to string in C++ with no luck.

If I using the to_string method, I end up with the error "to_string not a member of std".

标签: c++ string g++
6条回答
来,给爷笑一个
2楼-- · 2019-03-02 09:55

You can use std::stringstream

std::stringstream ss;
ss << "File - " << n << ".txt";

Since the constructor requires a char pointer, you need to convert it into a char pointer using

ofstream resultsFile(ss.str().c_str());
查看更多
聊天终结者
3楼-- · 2019-03-02 10:01

Using std::ostringstream:

std::ostringstream os;
os << "File - "  << nStr << ".txt";
std::ofstream resultsFile(os.str().c_str());

Using std::to_string (C++11):

std::string filename = "File - " + std::to_string(nStr) + ".txt";
std::ofstream resultsFile(filename.c_str());
查看更多
Lonely孤独者°
4楼-- · 2019-03-02 10:04

You want to use boost::lexical_cast. You also need to include any needed headers:

#include <boost/lexical_cast>
#include <string>
std::string nStr = boost::lexical_cast<std::string>(n);

then it's simply:

std::string file_name = "File-" + nStr + ".txt";

because std::strng plays nicely with string literals (e.g. ".txt").

查看更多
5楼-- · 2019-03-02 10:07

You could use a stringstream to construct the filename.

std::ostringstream filename;
filename << "File - " << n << ".txt";
resultsFile.open(filename.str().c_str());
查看更多
何必那么认真
6楼-- · 2019-03-02 10:08

For itoa, you are likely missing #include <stdlib.h>. Note that itoa is non-standard: the standard ways to format an integer as string as sprintf and std::ostringstream.

ofstream.open() takes a const char*, not std::string. Use .c_str() method to obtain the former from the latter.

Putting it together, you are looking for something like this:

ostringstream nameStream;
nameStream << "File - " << n << ".txt";
ofstream resultsFile(nameStream.str().c_str());
查看更多
地球回转人心会变
7楼-- · 2019-03-02 10:18

for itoa function

include <stdlib.h>

consider this link

http://www.cplusplus.com/reference/cstdlib/itoa/

查看更多
登录 后发表回答