我如何创建一个循环来检查用户的输入,看看它是否是一个现有的文件
How can i create a loop that checks a users input to see if it is an existing file?
我需要用户输入一个文件,只要用户输入存在的文件,文件就会循环。当用户输入一个不存在的文件时,程序将中断。
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
string currentfile;
int i = 0;
do {
cout << "Please enter a file name n";
cin >> currentfile;
cout << currentfile << "n";
ifstream myfile(currentfile);
if (myfile.good())
{
// display thenumber of characters, words, and lines in that file
myfile.close();
}
else {
cout << "break";
break;
}
i++;
} while(true);
// repeat while user enters valid file name
}
当我输入一个存在的文件时,myfile.good()
返回good,然后如果我尝试一个不存在的文件,myfile.good()
再次返回true。如果我启动程序,我首先尝试一个不存在的文件,then myfile.good()
返回false。
我不知道为什么在我输入一个有效的文件后,myfile.good()
将继续返回true。
您需要检查的是:
ifstream myfile(currentfile);
if (myfile) // myfile.is_open() is fine too...
{
// display thenumber of characters, words, and lines in that file
myfile.close();
}
else {
cout << "break";
break;
}
good():
检查流是否准备好输入/输出操作,其他成员函数用于检查特定状态
检查状态标志。
要测试文件是否成功打开,您可以使用:
myfile.is_open()
然后,如果是,您将执行如下检查:eof(),…,或good().
的例子:
ifstream myfile(currentfile);
if (myfile.is_open())
{
while ( myfile.good() ) // while ( !myfile.eof() ), ...
{
getline (myfile,line);
cout << line << endl;
}
myfile.close();
}
相关文章:
- 有没有办法在使用 GLFW 按下按键后只处理一个输入事件?
- 为什么在我的程序中输入另一个输入会给我不同的结果
- 当被一个输入分开时,有两个控制台输出同时显示
- 为什么此代码从标准输入中少一个输入?
- GoogleMock:如何根据另一个输入参数设置ArgReferee?
- 我的代码仅适用于一个输入.请指教
- 获取一个输入字符串,将其转换为其十六进制值,然后将其十六进制存储为 int
- "cin.get"停止了另一个输入函数,如"cin"..C++
- 使用getline()将字符串输入到程序中会导致下一个输入出现某种溢出
- 当我使用 cin 进行两个输入时,如何接受一个输入
- 如何从文件中一次读取一个输入,类似于在c++中使用cin/scanf从控制台读取输入
- 检查两个字符串是否相等,一个输入与另一个来自文件的输入相等
- STD :: Stringstream一次仅支持一个输入
- 如何在另一个输入语句中使用变量
- 一个输入多个输出文件C
- C 仅允许一个输入
- 整数输入 拒绝非整数输入并在C++中请求另一个输入
- 正在擦除文件中的最后一个输入
- 有没有一种方法可以测试一个输入是否是C++中的数字
- 你能定制一个输入的换行符(C++)吗