Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/157.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 使用if语句读取整行_C++ - Fatal编程技术网

C++ 使用if语句读取整行

C++ 使用if语句读取整行,c++,C++,好的,我有一个程序可以读取.txt文件 以下是.txt文件的示例内容: 1 load grades.csv 2 save grades.csv 3 show all 我将它作为字符串命令读入。在第1行中,我能够很好地读取命令load(该命令读取grades.csv文件),保存命令也是如此。但是对于下一行,我不确定如何将show all命令作为一个单词来阅读 这是我的代码: if (command == load) { in.ignore(); cout <<

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

以下是.txt文件的示例内容:

1 load grades.csv
2 save grades.csv
3 show all
我将它作为字符串
命令
读入。在第1行中,我能够很好地读取命令
load
(该命令读取
grades.csv
文件),保存
命令也是如此。但是对于下一行,我不确定如何将
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;
if(命令==load)
{
in.ignore();

cout不要使用仅检索到空格的
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 (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;
}
while(文件>>命令>>选项)
{
如果(命令==“加载”)

您在文件中读取的代码是否可能重复?
cin
只能读取到一个空格,因此要读取整行代码,您需要使用
getline
好的,我如何实现getline命令?
std::getline()
读取整行,直到达到EOL或EOF。使用
std::istringstream
解析读取的每行中的单个字。我使用while(!in.fail)循环。我无法更改该循环,因为它会干扰程序。您知道是否可以将其专门用于if语句。