【问题标题】:getline c++ problems with pipe overflow (?)管道溢出的getline c ++问题(?)
【发布时间】:2014-04-13 19:23:04
【问题描述】:

我用c++做了一个简单的程序来读取一个文件

#include <string>
#include <iostream>

using namespace std;

int main()
{
    string text;
    getline(cin, text);
    int textlength = 0;
    textlength = text.length(); 
    cout << text << endl;
    cout << text[3] << endl;
    cout << textlength << endl;
    int number=0;
    cout << "Enter a number: " << endl;
    cin >> number;
}

所以我在 Win 8.1 pro + mingw 中编译了这个程序,一切正常。接下来我通过在 cmd a.exe &lt; sample.txt 中写入来启动它。编译后的程序和txt必须在同一个文件夹中。

sample.txt 是包含该文本(一些随机字母、数字等)的文件:

iuhuefusifsduifhsdiufhfdliuhfdslhfdiufhfdslihfsdui 6 rer4 r4 r4t 4t46 t 4t43t 00 00 002 " & %

一切正常,直到最后一个 cin。那时我无法输入数字,因为跳过了输入过程。我还尝试在没有 getline 功能的情况下读出文本。相反,我只是简单地重复了一个 cin 过程,并将进度一个一个地保存在一个字符中。工作正常,直到最后的 cin 命令。它又跳过了。

以及如何解决这个问题的想法?

【问题讨论】:

标签: c++ overflow pipe getline


【解决方案1】:

此时,cin 仍在从您的文件 sample.txt 中读取 - 并且无法读取数字,因为 getline 已经读取了文件的所有内容。 在 sample.txt 中添加第二行可以让您读取一个数字(但请注意,如果输入不是数字,错误处理会变得非常棘手)。

【讨论】:

  • 感谢您的回答。然而,尽管添加了新行,它仍然跳过了 cin 命令。
  • 不,它不会跳过命令:它尝试读取 int 并失败 - 您可以检查 cin.good() 和 cin.fail() 状态指示器是否“不满意”。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-06
  • 1970-01-01
  • 2011-06-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多