3

我编写了这个函数,它应该从包含 ACII 十进制数字的文件中读取,并将它们转换为存储在 int 数组中的整数。这是该功能:

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*)'. 我不确定为什么它在我查看示例时不起作用,并且我使用它的方式完全相同。任何人都知道我可能做错了什么?

4

3 回答 3

7

atoi是一个接受 C 字符串而不是 C++ 的 C 函数std::string。您需要char*从字符串对象中获取原始数据以用作参数。方法是.c_str()

atoi(line.c_str());

的 C++ 等价物atoistd::stoi(C++11):

std::stoi(line);

此外,while (!file.eof())被认为是一种不好的做法。最好在表达式内执行 I/O 操作,以便返回流对象并在其后评估有效的文件条件:

while (std::getline(myfile, line))

但是,您的代码可以进一步改进。这是我的做法:

#include <vector>

void readf1()
{
    std::vector<int> 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 << "Read in the number: " << result << "\n\n";
    }
}
于 2013-10-08T22:15:10.503 回答
1

atoi()想要 a char *,而不是 a string

result = atoi(line.c_str());
于 2013-10-08T22:13:35.137 回答
1

您可以使用

result = atoi(line.c_str());
于 2013-10-08T22:13:51.637 回答