为什么我的编译器在尝试清除 CIN 缓冲区时抱怨
why is my compiler complaining when i try to clear the cin buffer
我正在编写一个程序,我正在尝试实现以下代码:
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()
调用,只使用getline
和std::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
你正在使用getline
和cin
的奇怪组合......如果您使用的是 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;
}
相关文章:
- C++字符*缓冲区的大小
- 为什么msgrcv()将垃圾字符馈送到缓冲区
- C++中的cin.ignore()函数不适用于整个流
- 使用动态分配的数组会导致代码分析发出虚假的C6386缓冲区溢出警告
- ostream过载时的缓冲区冲洗
- C++中的高效循环缓冲区,它将被传递给C样式数组函数参数
- 在while循环中输入带有std::cin的字符串后,控制台会输出大量胡言乱语
- istream std::cin如何修改自定义istream缓冲区
- C++ - 有什么方法可以将输入插入缓冲区/停止 cin.忽略需要输入?
- 如何从缓冲区x cin x次数
- 如何检查 cin 缓冲区是否包含相同的值 0.5 秒 (C++)
- 我可以做一个循环,直到“std::cin”在输入缓冲区中看到“”字符
- C++如何检查std::cin缓冲区是否为空
- cin.clear() 如何清除输入缓冲区
- 为什么我的编译器在尝试清除 CIN 缓冲区时抱怨
- 使用GetAsyncKeyState()时,C++正在清除cin缓冲区
- 对于std::cin缓冲区是否有大小限制?
- cin.get()缓冲区中的左换行字符
- 使用cin对象进行输入验证并清除缓冲区(c++)
- 需要帮助理解cin缓冲区的行为