我已经查过了所有可能的资源,但似乎找不到一个确切的答案。也许这显而易见,但我还是对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)”和“(fail)”):
( t
( f