该函数要求用户通过循环输入文件名的错误在哪里?

发布于 2024-12-13 12:26:57 字数 544 浏览 3 评论 0原文

以下函数在 Visual C++ 中运行正确,但在 G++ 中运行不正确。

void OpenFile(ifstream *input)
{
  string fileName = "";
  while (true) {
    cout << "Enter the filename: ";
    cin >> fileName;
    input->open(fileName.c_str());
    cin.clear();
    if (input->is_open()) break;
    cout << "The filename does not exist. Try again." << endl;
  }
}

g++中,如果用户第一次正确输入文件名,程序就会执行。然而,如果用户错误地输入文件名,该函数将提示用户再次尝试输入,当用户在后续尝试中输入正确的文件名时,光标将移动到下一行,并且程序暂停。错误是什么?同样,它在 Visual C++ 中正确运行。

The following function runs correctly in Visual C++ but not in G++.

void OpenFile(ifstream *input)
{
  string fileName = "";
  while (true) {
    cout << "Enter the filename: ";
    cin >> fileName;
    input->open(fileName.c_str());
    cin.clear();
    if (input->is_open()) break;
    cout << "The filename does not exist. Try again." << endl;
  }
}

In g++, if the user correctly enters the file name the first time, the program will execute. However, if the user incorrectly enters a file name, the function will prompt the user to enter another attempt, and when the user enters a correct file name on a subsequent attempt the cursor will move to the next line and the program pauses. What is the error? Again, this runs correctly in Visual C++.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

过去的过去 2024-12-20 12:26:57

cin.clear() 应该做什么?它应该重置任何错误
输入中的状态,但希望输入不处于错误状态。
(否则,您试图打开一个没有名称的文件。)一个未定义的文件。)

关于程序的不同行为,我怀疑它是
与系统(或库)缓冲输入的方式相关。这
cin>> fileName 通常不会返回,直到您输入换行符;
但是,它不会从输入流中删除换行符。
根据输入的缓冲方式,这可能会导致它阻塞
(虽然我认为不应该)。尝试循环播放提示时
输入,最好使用 std::getline,然后提取
从您已阅读的行中获取您需要的信息。 (在这种情况下,只需
去除两端的空白可能就足够了。)

What's the cin.clear() supposed to be doing? It shoud reset any error
state in the input, but hopefully, the input isn't in an error state.
(Otherwise, your trying to open a file without a name.)an undefined file.)

With regards to the varying behavior of the program, I suspect it is
linked to the way the system (or the library) is buffering input. The
cin >> fileName will typically not return until you enter a newline;
it will not, however, remove the newline from the input stream.
Depending on how input is buffered, this could cause it to block
(although I don't think it should). When trying to loop on prompted
input, it is probably best to use std::getline, then extract the
information you need from the line you have read. (In this case, just
stripping white space at either end would probably be sufficient.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文