当我尝试清除cin缓冲区时,为什么我的编译器会抱怨

时间:2013-11-06 08:44:55

标签: c++ buffer cin ignore

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

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属性来清除当前驻留在缓冲区中的换行符的缓冲区,但是当我尝试编译时,它给了我一堆乱码编译错误?为什么我能解决这个问题?

3 个答案:

答案 0 :(得分:1)

假设你包括

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

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

答案 1 :(得分:0)

您正在使用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;
}

答案 2 :(得分:0)

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

如果您可以拥有命令参数,我建议您删除cin >> ...部分以及cin.ignore()来电,并仅使用getlinestd::istringstream:< / p>

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: ";
}

参见例如这些参考文献:

相关问题