【问题标题】:The output console immediately closes upon display using user prompted input file [duplicate]使用用户提示的输入文件显示时,输出控制台立即关闭 [重复]
【发布时间】:2012-12-18 13:24:27
【问题描述】:

可能重复:
How to stop C++ console application from exiting immediately?

我正在使用 fstream 从用户那里收集输入文件。不幸的是,控制台只是短暂显示。

string filename;
cout << "input file" << endl ;

getline(cin,filename);

ifstream inputfile;
inputfile.open(filename);

char file_character ;
int counter = 0;

while (inputfile>> file_character) {

    inputfile.get(file_character);
    cout << file_character;

    //not what I'm totally doing but instead a quick example
    if (file_character == 'a')
    {
        counter++;
    }
}
cout << counter << endl;
inputfile.close();
return 0;

我需要读取输入文件中的每个字母并对每个字符进行多次检查。为什么我的控制台无法保持打开状态?

【问题讨论】:

  • 你在使用 Windows 吗?
  • 你永远不会检查任何东西。如果不能打扰,我们应该如何找出问题所在?

标签: c++ io ifstream


【解决方案1】:

您可以尝试从控制台启动程序。或者,您可以在退出main 之前暂停您的程序:例如,您可以等待用户输入一个字符,或者设置几秒钟的时间延迟。

顺便说一句,您的程序中有一个错误。 while (inputfile &gt;&gt; file_character) 已经将字符读入变量,所以当你转到inputfile.get(file_character) 时,你又读了一遍,因此丢失了一半的输入。

【讨论】:

    【解决方案2】:

    使用 windows,控制台在程序退出时关闭。

    在程序末尾附加system("Pause");,它会提示您在退出前按下一个键。

    一种通用的解决方案(适用于任何系统)是使用std::getchar(); 代替windows 独有的system("pause"); 从用户那里读取字符

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-30
      • 2016-05-10
      相关资源
      最近更新 更多