【问题标题】:Reading a full line with a if-statements用 if 语句读取整行
【发布时间】:2026-02-18 14:55:01
【问题描述】:

好的,所以我有一个读取 .txt 文件的程序。

这是 .txt 文件的示例内容:

1 load grades.csv
2 save grades.csv
3 show all

我已将它作为字符串 command 读入。在第 1 行中,我能够很好地读取命令 load(该命令读取 grades.csv 文件),save 命令也是如此。但是对于下一行,我不确定如何将show all 命令作为一个单词来阅读。

这是我的代码:

if (command == load)
   {
    in.ignore();
    cout << "load" << endl;
   }
else if (command == "show all")  //this is the error, it only reads in **save**
    cout << "show" << endl;
else
    cout << "save" << endl;

这是在 while 循环中运行的。我觉得我必须使用 ignore() 函数,但我不确定如何在 if-else 语句中实现它。

谢谢

【问题讨论】:

  • 你用什么代码读入文件? cin 只会读到一个空格,所以要读一整行你需要使用getline
  • 好的,我将如何实现 getline 命令?
  • std::getline() 读取整行,直到到达 EOL 或 EOF。使用std::istringstream 解析读取的每一行中的单个单词。

标签: c++


【解决方案1】:

如果每行总是有两个单词,则可以分别阅读:

while (file >> command >> option)
{
    if (command == "load")
        cout << "load " << option << endl;
    else if (command == "show" && option == "all")
        cout << "show all" << endl;
    else if (command == "save")
        cout << "save " << option << endl;
}

【讨论】:

    【解决方案2】:

    不要使用cin,它只会检索直到空格,而是使用:

    while( std::getline( cin, s ) ) 
    {
       // s will be a full line from your file.  You may need to parse/manipulate it to meet your needs
    }
    

    【讨论】:

    • 我使用了一个 while(!in.fail) 循环。我不能改变它,因为它会弄乱程序。你知道是否可以将它专门用于 if 语句。