为什么我的编译器在尝试清除 CIN 缓冲区时抱怨

why is my compiler complaining when i try to clear the cin buffer

本文关键字:缓冲区 CIN 清除 我的 编译器 为什么      更新时间:2023-10-16

我正在编写一个程序,我正在尝试实现以下代码:

int main(){
string inputcmd;

while (getline(cin, inputcmd)){
    cout << "TYPE A COMMAND" << endl;   
    cin >> inputcmd;
    cin.ignore (std::numeric_limits<std::streamsize>::max(), 'n'); 
    if (inputcmd == "make"){
        cout << "MAKING NEW PROJECT" << endl;
        get_project(cin);
    }
    else if (inputcmd == "retrieve"){
        cout << "RETRIEVING YOUR PROJECT" << endl;
    }
}
return 0;
}

我正在尝试使用 cin.ignore 属性来清除当前驻留在缓冲区中的换行符的缓冲区,但是当我尝试编译时,它给了我一堆乱码编译器错误? 为什么会这样,我该如何解决这个问题?

假设你包括

#include <string>
#include <iostream>
using namespace std;

然后我没有收到任何错误。

您需要按一个额外的换行符,因为您读取了两次输入。第一次是getline,第二次是cin >> ...

如果你可以对命令有参数,我建议你删除cin >> ...部分,连同cin.ignore()调用,只使用getlinestd::istringstream

std::cout << "Enter command: ";
while (std::getline(std::cin, line))
{
    std::istringstream iss(line);
    // Get the command
    std::string command;
    iss >> command;
    if (command == "make")
    {
        ...
    }
    ...
    std::cout << "Enter command: ";
}

这样,您也可以轻松地将空格分隔的参数获取到命令中。

是的,您有代码可以打印两次提示,但在我看来,这是一个较小且可以忽略不计的问题。


或者,如果你想更通用,使用例如std::vector来存储命令和参数,并做类似的事情

std::cout << "Enter command: ";
while (std::getline(cin, line))
{
    std::istringstream iss(line);
    std::vector<std::string> args;
    // Get the command and all arguments, and put them into the `args` vector
    std::copy(std::istream_iterator<std::string>(iss),
              std::istream_iterator<std::string>(),
              std::back_inserter(args));
    if (args[0] == "make")
    {
        ...
    }
    ...
    std::cout << "Enter command: ";
}

例如,请参阅以下参考资料:

  • std::copy
  • std::istream_iterator
  • std::back_inserter

你正在使用getlinecin的奇怪组合......如果您使用的是 getline ,则根本不需要调用cin.ignore。不要像以前那样混合两者,否则会得到令人困惑的结果。

此示例可能按照您的要求运行:

#include <string>
#include <iostream>
using namespace std;
int main(){
  string inputcmd;
  bool running = true;
  while (running){
    cout << "TYPE A COMMAND" << endl;
    getline(cin, inputcmd);
    if (inputcmd.substr(0, inputcmd.find(" ")) == "make"){
      if(inputcmd.find(" ")!=string::npos){
        inputcmd = inputcmd.substr(inputcmd.find(" ")+1);
        cout << "MAKING NEW PROJECT: " << inputcmd << endl;
        //get_project(cin);
      }else{
        cout << "make: not enough arguments" << endl;
      }
    }else if (inputcmd == "retrieve"){
      cout << "RETRIEVING YOUR PROJECT" << endl;
    }else if(inputcmd == ""){
      running = false;
    }
  }
  return 0;
}