从文件中读取数据并转换为整数?

4

我写了一个函数,用于从包含ASCII十进制数的文件中读取并将它们转换为存储在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*)'。我不确定为什么它不能正常工作,因为我查看了示例,并且我正在完全相同的方式使用它。有人知道我可能做错了什么吗?


你能够使用 cout << line 并发布它是什么吗? - David says Reinstate Monica
3个回答

7

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

atoi(line.c_str());

atoi的C++等效函数是std::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";
    }
}

不仅回答了我的问题,还提供了改进的代码,并展示了更好的习惯要求!谢谢! - Andy

1
"atoi()"需要一个char *,而不是一个string。"
result = atoi(line.c_str());

1
你可以使用

标签


result = atoi(line.c_str());

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接