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

时间:2015-09-16 15:26:54

标签: c++ string is-empty

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

  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

2 个答案:

答案 0 :(得分:2)

当您使用fileName初始化" "时,不会执行检查空虚的while循环(因此它是非空)。使用do...while()或只是不初始化std::string(不需要它。)

答案 1 :(得分:2)

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

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

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