2

我从文件中读取了一行,我正在尝试将其转换为 int。出于某种原因atoi()(将字符串转换为整数)不接受 astd::string作为参数(字符串、c-strings 和 char 数组可能存在一些问题?) - 我如何才能atoi()正常工作以便解析这个文本文件?(将从中提取大量整数)。

代码:

int main()
{
    string line;
    // string filename = "data.txt";
    // ifstream file(filename)
    ifstream file("data.txt");
    while (file.good())
    {
        getline(file, line);
        int columns = atoi(line);
    }
    file.close();
    cout << "Done" << endl;
}

导致问题的行是:

int columns = atoi(line);

这给出了错误:

错误:无法将参数“1”转换'std::string''const char*'“int atop(const char*)

我如何使atoi正常工作?

编辑:谢谢大家,它的工作原理!新代码:

int main()
{
string line;
//string filename = "data.txt";
//ifstream file (filename)
ifstream file ("data.txt");
while ( getline (file,line) )
{
  cout << line << endl;
  int columns = atoi(line.c_str());
  cout << "columns: " << columns << endl;
  columns++;
  columns++;
  cout << "columns after adding: " << columns << endl;
}
file.close();
cout << "Done" << endl;
}

还想知道为什么 string filename = "data.txt"; ifstream 文件(文件名)失败,但是

    ifstream file("data.txt");

作品?(我最终将从命令行读取文件名,因此需要使其不是字符串文字)

4

3 回答 3

7

为此目的存在 c_str 方法。

int columns = atoi(line.c_str());

顺便说一句,您的代码应该阅读

while (getline (file,line))
{
    ...

仅仅因为文件是“好”并不意味着下一个getline 会成功,只是最后一个getline 成功了。在您的 while 条件中直接使用 getline 来判断您是否确实阅读了一行。

于 2013-05-02T19:39:20.713 回答
2

int columns = atoi(line.c_str());

于 2013-05-02T19:39:37.657 回答
1

使用line.c_str()而不仅仅是line

这个 atoi 需要一个const char*not astd::string

于 2013-05-02T19:39:19.433 回答