【发布时间】: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 < sample.txt 中写入来启动它。编译后的程序和txt必须在同一个文件夹中。
sample.txt 是包含该文本(一些随机字母、数字等)的文件:
iuhuefusifsduifhsdiufhfdliuhfdslhfdiufhfdslihfsdui 6 rer4 r4 r4t 4t46 t 4t43t 00 00 002 " & %
一切正常,直到最后一个 cin。那时我无法输入数字,因为跳过了输入过程。我还尝试在没有 getline 功能的情况下读出文本。相反,我只是简单地重复了一个 cin 过程,并将进度一个一个地保存在一个字符中。工作正常,直到最后的 cin 命令。它又跳过了。
以及如何解决这个问题的想法?
【问题讨论】:
-
如果之后需要使用
cin,请忘记通过<传递文件。尝试通过参数列表传递文件名并通过ifstream打开它。