从文件读取然后转换为int?

时间:2013-10-08 22:11:16

标签: c++

我写了这个函数,它应该从包含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*)'。我不确定为什么它不起作用,因为我看了一些例子,我使用它完全一样。任何人都知道我可能做错了什么?

3 个答案:

答案 0 :(得分:6)

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";
    }
}

答案 1 :(得分:1)

atoi()需要char *,而不是string

result = atoi(line.c_str());

答案 2 :(得分:1)

您可以使用

result = atoi(line.c_str());
相关问题