我希望用户输入文件名,如果文件存在,则打印出文件的所有内容。
例如,此时未注释的代码采用用户输入的文件名。example.txt 并打印出文件的大部分(不是最后一个词?)。我试图通过使用字符串(注释代码是尝试)来实现这一点,但显然它不正确。
我还想知道是否可以将 .txt 自动添加到用户输入的末尾,以便控制台可以询问 - “我们应该找到关于哪个主题的更多信息”用户输入“数学”,它将打开“math.txt”
这是我尝试过的:
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
using namespace std;
int main() {
char filename[50];
//string getcontent;
ifstream name;
cin.getline(filename, 50);
name.open(filename);
if (!name.is_open()) {
exit(EXIT_FAILURE);
}
char word[50];
name >> word;
while (name.good()) {
cout << word << " ";
name >> word;
}
//if (!name.is_open()) {
//while (! filename).eof())
//{
//getline(name, getcontent)
//cout << getcontent << endl;
//}
//exit(EXIT_FAILURE); //comes from cstdlib
//}
//}
system("pause");
return 0;
}
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
using namespace std;
int main() {
string filename;
string getcontent;
ifstream name;
cin >> filename;
filename.append(".txt"); // add extension.
name.open(filename);
if (!name.is_open()) {
exit(EXIT_FAILURE);
}
while (true)
{
getline(name, getcontent);
if (name.eof()) break;
cout << getcontent << endl;
}
return 0;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句