C++ 询问用户文件名,如果他们什么都不输入,我该如何正确地重新提示

C++ ask user for file name, if they enter nothing how do i correctly re-prompt

创建一个程序,在给定文件存在之前提示用户,到目前为止,如果文件存在,它会重新提示他们。但是当我提示用户输入文件名时,他们决定按回车键,我得到的只是白色 space,直到我输入字符。当用户决定不输入任何内容时,如何重新提示。

  while(fileName.empty())/*********************/
            {
            cout<<"Enter file name: ";
            cin>> fileName;
            }

^给定空字符串时尝试重新提示^

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
        string line;
        ifstream inData;
        ofstream outData;
        string fileName = " ";
        char digit;
        float num[1000];
        float sum[10];
        int num_count;
        int  i = 0;
        float user_num,tot,result;


/*Program will ask user for file name, read the file
sum the first 3 numbers of the file, then will prompt
the user for a fourth number in which it will sum all
numbers and print the average*/


        while(fileName.empty())/*********************/
        {
        cout<<"Enter file name: ";
        cin>> fileName;
        }

        inData.open(fileName.c_str());
        /*outData.open(fileName.c_str());*/

        while(!inData.is_open())
        {
        cout<<"Please enter a valid file name or path: ";
        cin>>fileName;
        inData.open(fileName.c_str());
        }


        if (inData.is_open())
         {
            while (inData.good())
            {
                inData >> digit;
                num[i] = digit - '0';
                i++;
                num_count = i - 1;
            }
        inData.close();



        cout<<"Enter fourth number: ";
        cin>> user_num;
        num[3] = user_num;


        for(int a = 0; a <= 3; a++)
        {
            tot += num[a];
        }


        result = tot/4.0;

        cout<<"The average of the four numbers is: "<<result<<'\n';

        }

        return 0;
}

这是我的测试文件

jim.txt

2 44 3

当您用 " " 初始化 fileName 时,您检查是否为空的 while 循环将不会执行(即使是一次)(所以它 不为空 ).使用 do...while() 或干脆不初始化 std::string (没有必要。)

像这样尝试使用 getline 而不是 operator<<;

while (fileName.empty())
{
  cout << "Enter file name: ";
  char c[255];
  cin.getline(c, 255);
  fileName = string(c);
}

ps:刚刚注意到来自@DawidPi 的评论和同样的建议:)