【问题标题】:How to have a.out file read text file through terminal by typing "a.out < textfilename.txt"如何通过键入“a.out < textfilename.txt”让 a.out 文件通过终端读取文本文件
【发布时间】:2015-05-11 09:04:34
【问题描述】:

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

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

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

当我使用 getline 而不是使用 fstream 时,它会读取文件而不是整个文件(直到它到达 EOF)。我不确定我应该如何编写代码。 (作业已提交,仅供参考)

【问题讨论】:

  • "a.out" 是某些编译器(例如 GCC)的默认输出文件名 - 不要与同名文件格式混淆(现已弃用)。

标签: c++ command-line-arguments


【解决方案1】:

当有人使用&lt; 字符进行重定向时,该文件成为标准输入。所以cin 将包含text.txt 的内容。由于 cin 是 istream 你可以这样做:

while (cin.get(b)) {
   // what you've got now...
}

【讨论】:

    猜你喜欢
    • 2014-08-20
    • 2014-06-11
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 2019-12-20
    • 1970-01-01
    相关资源
    最近更新 更多