C ++ int to string,连接字符串 [英] C++ int to string, concatenate strings
问题描述
我是C ++的新手,正在开发一个简单的项目。基本上我遇到一个问题是在文件名中创建一个带有一个数字(int)的文件。正如我看到的,我必须首先将int转换为字符串(或char数组),然后将这个新的字符串与文件名的其余部分连接。
在这里是我的代码到目前为止无法编译:
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));
这会产生几个编译错误(在Linux中编译):
- itoa未在此范围内声明
- 没有匹配的函数调用'std :: basic_ofstream char,std :: char_traits char :: open(std :: basic_string char,std :: char_traits char,std :: allocator char)'
此处: c字符串和int连接
,此处为:最简单的方法将C ++中的int转换为字符串,没有运气。 / p>
如果我使用to_string方法,我最终得到错误to_string不是std的成员。
您可以使用 stringstream
p>
std :: ostringstream filename;
filename<< File - << n<< 。文本;
resultsFile.open(filename.str()。c_str());
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):
- itoa not declared in this scope
- 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".
You could use a stringstream
to construct the filename.
std::ostringstream filename;
filename << "File - " << n << ".txt";
resultsFile.open(filename.str().c_str());
这篇关于C ++ int to string,连接字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!