C++;int到字符串,连接字符串 我是C++新手,工作简单。基本上,我遇到的问题是创建一个文件名中带有数字(int)的文件。在我看来,我必须首先将int转换为字符串(或char数组),然后将这个新字符串与文件名的其余部分连接起来
以下是我至今未能编译的代码:C++;int到字符串,连接字符串 我是C++新手,工作简单。基本上,我遇到的问题是创建一个文件名中带有数字(int)的文件。在我看来,我必须首先将int转换为字符串(或char数组),然后将这个新字符串与文件名的其余部分连接起来,c++,string,g++,C++,String,G++,以下是我至今未能编译的代码: 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::b
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中编译):
如果我使用to_string方法,我最终会出现错误“to_string not asmember of std” 您想使用
boost::lexical\u cast
。您还需要包括任何需要的标题:
#include <boost/lexical_cast>
#include <string>
std::string nStr = boost::lexical_cast<std::string>(n);
因为
std::strng
可以很好地处理字符串文本(例如“.txt”)。您想使用boost::lexical\u cast
。您还需要包括任何需要的标题:
#include <boost/lexical_cast>
#include <string>
std::string nStr = boost::lexical_cast<std::string>(n);
由于
std::strng
可以很好地处理字符串文字(例如“.txt”)。对于itoa
,您可能缺少\include
。请注意,itoa
是非标准的:将整数格式化为字符串的标准方法是sprintf
和std::ostringstream
of stream.open()
采用const char*
,而不是std::string
。使用.c_str()
方法从后者获取前者
把它放在一起,你正在寻找这样的东西:
ostringstream nameStream;
nameStream << "File - " << n << ".txt";
ofstream resultsFile(nameStream.str().c_str());
ostringstream名称流;
nameStream对于itoa
,您可能缺少#include
。请注意,itoa
是非标准的:将整数格式化为字符串的标准方法是sprintf
和std::ostringstream
of stream.open()
采用const char*
,而不是std::string
。使用.c_str()
方法从后者获取前者
把它放在一起,你正在寻找这样的东西:
ostringstream nameStream;
nameStream << "File - " << n << ".txt";
ofstream resultsFile(nameStream.str().c_str());
ostringstream名称流;
nameStream您可以使用stringstream
来构造文件名
std::ostringstream filename;
filename << "File - " << n << ".txt";
resultsFile.open(filename.str().c_str());
std::ostringstream文件名;
文件名您可以使用stringstream
来构造文件名
std::ostringstream filename;
filename << "File - " << n << ".txt";
resultsFile.open(filename.str().c_str());
std::ostringstream文件名;
itoa函数的文件名
include <stdlib.h>
包括
以这一联系为例
对于itoa功能
include <stdlib.h>
包括
以这一联系为例
使用:
使用:
您可以使用std::stringstream
std::stringstream ss;
ss << "File - " << n << ".txt";
您可以使用std::stringstream
std::stringstream ss;
ss << "File - " << n << ".txt";
或者,如果您没有任何一个,请使用stringstream。如果您没有任何一个,请使用stringstream。这看起来很有希望。然而,当我编译代码时,我得到了一个错误:“聚合'std::ostringstream filename'的类型不完整,无法定义”我无法识别该错误。您需要将
#包含在源文件的顶部。这看起来很有希望。然而,当我编译代码时,我得到了一个错误:“聚合'std::ostringstream filename'的类型不完整,无法定义”我无法识别该错误。您需要将
#包含在源文件的顶部。如果您负担得起C++11,将整数转换为字符串的更简单方法是使用std::to_string
。请看我的答案中的一个例子。如果你买得起C++11,将整数转换成字符串的一种更简单的方法是使用std::to_string
。请参阅我的答案以获取示例。#包括,不包括。#包括,不包括。