gpt4 book ai didi

c++ - 如何通过键入 "a.out < textfilename.txt"让 a.out 文件通过终端读取文本文件

转载 作者:行者123 更新时间:2023-11-30 05:43:34 24 4
gpt4 key购买 nike

我是编程新手,找不到问题的答案。

这是我必须打开我的程序并在终端上运行它时读取我想要的文本文件的代码:

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...
}

关于c++ - 如何通过键入 "a.out < textfilename.txt"让 a.out 文件通过终端读取文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30158266/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com