我编写了这个函数,该函数从包含ACII十进制数字的文件中读取数据,并将这些数字转换为存储在整型数组中的整数。下面是该函数:
void readf1()
{
int myintArray[100];
int i = 0;
int result;
string line = "";
ifstream myfile;
myfile.open("f1.txt");
if(myfile.is_open()){
//while not end of file
while(!myfile.eof()){
//get the line
getline(myfile, line);
/* PROBLEM HERE */
result = atoi(line);
myintArray[i] = result;
//myintArray[i]
cout<<"Read in the number: "<<myintArray[i]<<"\n\n";
i++;
}
}
}问题是atoi不工作。我得到的错误是cannot convert 'std::string {aka std::basic_string<char>}' to 'const char*' for argument '1' to 'int atoi(const char*)'。我不确定为什么它不工作,因为我看了例子,我正在使用它完全相同。有人知道我可能做错了什么吗?
发布于 2013-10-09 06:15:11
atoi是一个C函数,它接受C字符串,而不是C++ std::string。您需要从string对象中获取原始char*以用作参数。这样做的方法是.c_str()
atoi(line.c_str());
atoi的C++等价物是std::stoi (C++11):
std::stoi(行);
此外,while (!file.eof())被认为是一种糟糕的做法。最好是在表达式内部执行I/O操作,以便返回流对象,然后评估有效的文件条件:
while (std::getline(myfile,line))
但是,您的代码还可以进一步改进。下面是我会怎么做:
#include void readf1() { std::vector myintArray;std::string line;std::ifstream myfile("f1.txt");for (int result;std::getline(myfile,line);result = std::stoi(line)) { myintArray.push_back( result );std::cout <<“读入的编号:”<< result << "\n\n";} }
发布于 2013-10-09 06:13:35
atoi()要的是char *,而不是string
result = atoi(line.c_str());发布于 2013-10-09 06:13:52
您可以使用
result = atoi(line.c_str());https://stackoverflow.com/questions/19259418
复制相似问题