如何通过终端输入 "a.out < textfilename.txt" 让 a.out 文件读取文本文件
How to have a.out file read text file through terminal by typing "a.out < textfilename.txt"
我是编程新手,找不到问题的答案。
这是我必须打开我的程序并在终端上 运行 读取我想要的文本文件的代码:
using namespace std;
int main(int argc, string *argv[])
{
string fileName;
getline(cin, fileName);
ifstream infile(fileName.c_str());
int total[26] = {0};
if (!infile)
{
cout << "Error opening file" << endl;
return 0;
}
char b;
while (infile.get(b))
{
if (isalpha(b))
{
b = toupper(b);
int index = b - 'A';
total[index]++;
}
}
我可以 运行 程序并键入我想通过终端打开的文件,但我的教师的程序可以通过在终端中键入以下内容来打开文件:
a.out < text.txt
当我使用 getline 而不是使用 fstream 时,它读取文件而不是整个文件(直到到达 EOF)。我不确定我应该如何编写代码。 (作业已提交,仅供本人参考)
当有人使用 <
字符进行重定向时,该文件 成为 标准输入。所以 cin
将包含 text.txt
的内容。由于 cin 是 istream
你可以这样做:
while (cin.get(b)) {
// what you've got now...
}
我是编程新手,找不到问题的答案。
这是我必须打开我的程序并在终端上 运行 读取我想要的文本文件的代码:
using namespace std;
int main(int argc, string *argv[])
{
string fileName;
getline(cin, fileName);
ifstream infile(fileName.c_str());
int total[26] = {0};
if (!infile)
{
cout << "Error opening file" << endl;
return 0;
}
char b;
while (infile.get(b))
{
if (isalpha(b))
{
b = toupper(b);
int index = b - 'A';
total[index]++;
}
}
我可以 运行 程序并键入我想通过终端打开的文件,但我的教师的程序可以通过在终端中键入以下内容来打开文件:
a.out < text.txt
当我使用 getline 而不是使用 fstream 时,它读取文件而不是整个文件(直到到达 EOF)。我不确定我应该如何编写代码。 (作业已提交,仅供本人参考)
当有人使用 <
字符进行重定向时,该文件 成为 标准输入。所以 cin
将包含 text.txt
的内容。由于 cin 是 istream
你可以这样做:
while (cin.get(b)) {
// what you've got now...
}