[英]C++ cin with file instead of user input
我已经查找了所有资源的感觉,但似乎找不到这个问题的可靠答案。 也许很明显,我还是C ++的新手。
我有以下功能性主要方法:
int main()
{
char firstChar, secondChar;
cin >> firstChar;
cin >> secondChar;
cout << firstChar << " " << secondChar;
system("pause"); // to wait for user input; allows the user to see what was printed before the window closes
return 0;
}
这将导致控制台等待输入。 用户输入一些东西。 在这种情况下(test)
。 输出为:
( t
我想更改此设置,以使输入来自文件,并且可以对每一行执行相同的方法,而不仅仅是一次。
我尝试了以下多种变体:
int main(int argc, char* argv[])
{
ifstream filename(argv[0]);
string line;
char firstChar, secondChar;
while (getline(filename, line))
{
cin >> firstChar; // instead of getting a user input I want firstChar from the first line of the file.
cin >> secondChar; // Same concept here.
cout << firstChar << " " << secondChar;
}
system("pause"); // to wait for user input; allows the user to see what was printed before the window closes
return 0;
}
这仅对文件中的每一行运行一次while循环,但仍然需要在控制台中输入内容,而绝不操纵文件中的数据。
文件内容:
(test)
(fail)
所需的自动输出(无需让用户手动输入(test) and (fail)
:
( t
( f
最终编辑
看到输入后,我会做这样的事情
int main(int argc, char* argv[])
{
ifstream exprFile(argv[1]); // argv[0] is the exe, not the file ;)
string singleExpr;
while (getline(exprFile, singleExpr)) // Gets a full line from the file
{
// do something with this string now
if(singleExpr == "( test )")
{
}
else if(singleExpr == "( fail )") etc....
}
return 0;
}
您知道文件中的全部输入是什么,因此可以一次测试整个字符串,而不必逐个字符地进行测试。 然后,一旦有了这个字符串,就采取相应的行动
流提取运算符或“ >>”将从流中读取,直到找到空白为止。 在C ++中,cin和cout分别是istream和ostream类型的流。 在您的示例中,exprFile是一个istream,当打开文件时,它成功连接到您提到的文件。 要一次从流中获取一个角色,您可以执行以下操作,
char paren;
paren = cin.get(); //For the cin stream.
paren = exprFile.get(); //for the exprStream stream, depending on your choice
为了获得更多的信息,经过这
您可以这样:
int main(int argc, char* argv[])
{
ifstream filename(argv[0]);
string line;
char firstChar, secondChar;
while (getline(filename, line))
{
istringstream strm(line);
strm >> firstChar;
strm >> secondChar;
cout << firstChar << " " << secondChar;
}
system("pause"); // to wait for user input; allows the user to see what was printed before the window closes
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.