c++ - 从 .txt 文件中读取一行并插入到变量中

标签 c++ ifstream getline

我正在尝试编写一个程序,它将只读取我的文本文件的第一行,然后将该数字输入到一个 int 变量中。但我对如何去做感到困惑。

    int highscore; // Starting highscore

  ifstream myfile ("highscore.txt");
  if (myfile.is_open())
  {
    while ( myfile.good() )
    {
      getline(myfile,highscore);
      cout << highscore << endl;
    }
    myfile.close();
  }

但由于某种原因我得到了错误。 |25|错误:没有匹配函数来调用 'getline(std::ifstream&, int&)'|

最佳答案

如果将 getline 替换为:

if (myfile >> highscore)
    cout << "Read " << highscore << '\n';
else
    cout << "Couldn't read an int\n";

您将能够将 int 读入 highscore。您需要使用 getline 吗?

关于c++ - 从 .txt 文件中读取一行并插入到变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13225116/

相关文章:

c++ - 如何中断读取此文本文件(使用 ifstream)? C++

c++ - 我可以在 C++ 函数 getline 中使用 2 个或更多分隔符吗?

c++ - 在头文件中声明 Qt 类

c++ - 数组初始化时出现段错误

c++ - 用 C++ 编写可动态加载的组件

c++ - 尝试读取二进制文件 C++ 时出现问题

c++ - 返回值优化不适用于 const unique_ptr 成员?

c++ - ifstream 不从 C++ 文件中读取值

awk - awk 可以根据单独的规范文件替换字段吗?

c++ - 使用 cin.get 提取特定数量的字符并确保正确