c++ - 如何将文件输入 C++ 并比较控制台输入

标签 c++ file input fstream

我正在做我的家庭作业,但我卡住了,因为在作业中,我们必须要求用户输入文件名,但还要输入 wc cc 或 lc(文件的字数、字符数和行数) 。例如,wc filename.txt。我想检查文件以查看其是否有效,我知道我知道如何比较用户输入以确定要运行的不同类型的函数,但我不明白你是如何可以一起做。有什么想法吗?这就是我目前的想法。

#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int main()
{
string line;
string file;

ifstream input; //input file stream
int i;

cout << "Enter a file name" << endl;

while(true){

    cout << ">" ;
    getline(cin,file);

    input.open(file.c_str());

     if (input.fail()) {
        cerr << "ERROR: Failed to open file " << file << endl;
        input.clear();
     }
     else {
        i = 0;
        while (getline(input, line))

            if(line == "wc"){

            cout << "The word count is: " << endl;
    }
        else if(line == "cc"){

            cout << "The character count is: " << endl;
    }
        else if(line == "lc"){

            cout << "The line count is: " << endl;
    }
        else if(line == "exit"){

            return 0;
    }
        else{

            cout << "----NOTE----" << endl;
            cout << "Available Commands: " << endl;
            cout <<"lc \"filename\"" << endl;
            cout <<"cc \"filename\"" << endl;
            cout <<"wc \"filename\"" << endl;
            cout <<"exit" << endl;
    }



     }



}


return 0;
}

void wordCount(){
   //TBD
}

void characterCount(){
    //TBD

}

void lineCount(){
  //TBD

}

最佳答案

您必须在用户输入的命令和文件名之间找到空格,然后在找到空格的地方拆分字符串。像这样

cout << "Enter a command\n";
string line;
getline(cin, line);
// get the position of the space as an index
size_t space_pos = line.find(' ');
if (space_pos == string::npos)
{
   // user didn't enter a space, so error message and exit
   cout << "illegal command\n";
   exit(1);
}
// split the string at the first space
string cmd = line.substr(0, space_pos);
string file_name = line.substr(space_pos + 1);

这是未经测试的代码。

你可以做得更好,例如,如果用户在命令和文件名之间输入两个空格,这将不起作用。但是这种工作很快就会变得非常乏味。由于这是一项任务,我很想继续做更有趣的事情。如果有时间,您随时可以回来改进。

关于c++ - 如何将文件输入 C++ 并比较控制台输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12323744/

相关文章:

c++ - 将自定义标签添加到 TIFF 文件

c++ - 我遇到了错误,您不应该得到它。

linux - 在 Linux 上将一个文件的内容插入到另一个文件

jquery - 将输入值发送到 JQuery 函数

html - 如何从 href 生成输入类型 ="submit"?

c++ - 使用 boost::optional boost program_options

c++ - Z3优化: detect unboundedness via API

c - 如何使用C计算文件中不同类型字符的数量。

ruby - 如何使用 Ruby 通过 HTTP 下载文件?

用于将正则表达式匹配转换为按钮的 Javascript 库