管道溢出的getline c ++问题(?)

时间:2014-04-13 19:23:05

标签: c++ overflow pipe getline

我用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 < sample.txt来开始它。已编译的程序和txt必须位于同一文件夹中。

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

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

一切正常,直到最后一个cin点。此时我无法输入数字,因为跳过了输入过程。我还尝试在没有getline函数的情况下读出文本。相反,我只是重复一个cin过程并在char中逐个保存进度。工作得很好,直到最后的cin命令。它再次跳过了。

想法如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

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