2013-10-08 17 views
1

我写了这个函数,该函数应该从包含ACII十进制数字的文件中读取,并将它们转换为存储在int数组中的整数。这是这个功能:从文件读取然后转换为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*)'。我不确定为什么它不能正常工作,因为我查看了示例,而且我正在使用它完全相同。任何人都知道我可能做错了什么?

+0

你能'的cout << line'并张贴它是什么? –

回答

5

atoi是接受C-字符串,而不是C++ std::string C函数。您需要从字符串对象获取原始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"; 
    } 
} 
+0

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

1

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

result = atoi(line.c_str()); 
1

您可以使用

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