c++ - 不能让 atoi 接收字符串(字符串与 C 字符串?)

标签 c++ string file-io atoi

我从一个文件中读取了一行,我正在尝试将其转换为一个整数。出于某种原因 atoi() (将字符串转换为整数)不会接受 std::string 作为参数(可能是字符串 vs c-strings vs 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);

给出了错误:

error: cannot convert 'std::string' to 'const char*' for argument '1' to '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;
}

也想知道为什么 字符串文件名 = "data.txt"; ifstream 文件(文件名) 失败了,但是

    ifstream file("data.txt");

有效吗? (我最终会从命令行读取文件名,所以需要让它不是字符串文字)

最佳答案

c_str 方法的存在就是为了这个目的。

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

顺便说一下,你的代码应该是这样的

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

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

关于c++ - 不能让 atoi 接收字符串(字符串与 C 字符串?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16346332/

相关文章:

java - 单击按钮时运行命令行代码

c++ - C++ 文件 I/O 问题

c++ - 如何将 VC6 项目转换为 Unicode

c++ - g++ 链接器错误:获取 std::hash 的 undefined reference 错误

c - 带有永不返回的 C 字符串的函数

C 用指针在字符串中查找子字符串

python - 删除文件(如果存在); Python

c++ - GSL Dilogarithm函数在C++中的使用

c++ - 运行 valgrind

java - 如果字符串是否在池中创建,如何确认(或获取字符串的对象表示)?