使用ifstream计算单词的外观 我从Stanley B. Lippman的C++第五底稿中读到这个代码,由 此代码用于计算字母在文件中出现的时间

使用ifstream计算单词的外观 我从Stanley B. Lippman的C++第五底稿中读到这个代码,由 此代码用于计算字母在文件中出现的时间,c++,ifstream,C++,Ifstream,我想知道主函数的两个参数的函数 什么是infle.openargv[1],infle 此外,infle.open的参数不能是常量吗?如果不是,如何更改要从控制台读取的文件,而不是从源代码读取的文件。 代码如下: //enter code here void runQueries(ifstream &infile) { // infile is an ifstream that is the file we want to query TextQuery tq(infile

我想知道主函数的两个参数的函数 什么是infle.openargv[1],infle

此外,infle.open的参数不能是常量吗?如果不是,如何更改要从控制台读取的文件,而不是从源代码读取的文件。 代码如下:

//enter code here
void runQueries(ifstream &infile)
{
    // infile is an ifstream that is the file we want to query
    TextQuery tq(infile);  // store the file and build the query map
    // iterate with the user: prompt for a word to find and print results
    while (true) {
         cout << "enter word to look for, or q to quit: ";
         string s;
         // stop if we hit end-of-file on the input or if a 'q' is entered
         if (!(cin >> s) || s == "q") break;
         // run the query and print the results
         print(cout, tq.query(s)) << endl;
         }
}

// program takes single argument specifying the file to query

//enter code here 
int main(int argc, char **argv)
{
    // open the file from which user will query words

    ifstream infile;

    // open returns void, so we use the comma operator XREF(commaOp) 
    // to check the state of infile after the open

    if (argc < 2 || !(infile.open(argv[1]), infile)) {
        cerr << "No input file!" << endl;
        return EXIT_FAILURE;

    }

    runQueries(infile);

    return 0;

}
我想知道主函数的两个参数的函数 它们分别是int argc中的参数数和指向参数const char*argv[]的指针数组

请注意,const char*argv[]和const char**argv是等效的,但我认为前者更易于阅读

argv[0]通常包含运行程序的可执行文件的名称

在本例中,程序希望第二个参数argv[1]是要打开的文件的路径

例如,如果您以这种方式运行程序:

$ myprogram file.txt
然后

什么是infle.openargv[1],infle 这不是它的拼写方式。实际上是infle.openargv[1],infle。这是在注释中解释的一种有点复杂的方法,用于打开文件并检查它是否正确打开。这本可以改写为:

if (argc >= 2) {
    infile.open(argv[1]);
    if (!infile) {
        //handle error
    }
} else {
    // handle error
}
但正如您所看到的,这需要在两个地方使用错误处理

坦率地说,我个人不会这样写:

if (argc < 2)
    throw std::runtime_exception("Requires a filename");

ifstream infile(argv[1]); // at this point we can safely assume we can dereference argv[1]

if (!infile)
    throw std::runtime_exception ("Cannot open file");
如果我没记错的话,这本书在后面的阶段引入了异常处理,所以现在不必全部更改

此外,infle.open的参数不能是常量吗? 如果函数需要常量参数,则也可以将非常量参数传递给它,但引用除外。但是,您已经在从console标准输入读取文件名,因此我看不出这里有问题。

argv[1]是传递给程序的第一个命令行参数。例如foo file.txt。
if (argc < 2)
    throw std::runtime_exception("Requires a filename");

ifstream infile(argv[1]); // at this point we can safely assume we can dereference argv[1]

if (!infile)
    throw std::runtime_exception ("Cannot open file");