而循环错误c ++

0 c++ loops while-loop visual-c++

我有一个while循环,在输入位置或文件名之前抛出异常.这是代码:

find.cpp

  cout << "enter file name or  location> " << flush;
  while (true)
  {
  string thefilename;
  getline( cin, thefilename );
  thefile.open( thefilename.c_str() );


  if (thefile) break;
  cout << "Invalid file. Please enter  file name or location> " << flush;

  }


  while(getline(thefile, temp))
        cout << temp << endl;
    thefile.clear();
    thefile.open("blabla.txt");


    cout << endl;
    thefile.close();
    system("pause");

    return 0;
             }
Run Code Online (Sandbox Code Playgroud)

当我跑这个我得到

      enter file name or location>Invalid file. Please enter  file name or location>
Run Code Online (Sandbox Code Playgroud)

代替

      enter file name or location>
Run Code Online (Sandbox Code Playgroud)

Die*_*ühl 5

你几乎肯定省略了有趣的代码:在输入文件名之前发生了什么!可能在它之前是一些格式化的输入(即,使用std::cin >> value),例如,读取数字:格式化的输入在第一个不匹配格式的字符处停止.例如,它在因使用回车键输入值而遇到的换行符处停止.

要解决这个问题,你应该摆脱领先的空白,例如,使用std::ws操纵器:

while (std::getline(std::cin >> std::ws, thefilename)) {
    ...
}
Run Code Online (Sandbox Code Playgroud)

或者,您可能希望ignore()在前面的输入之后包含换行符的所有内容:

std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
while (std::getline(std::cin, thefilename)) {
    ...
}
Run Code Online (Sandbox Code Playgroud)