退出选项和 while 循环C++
Quit-option and while loop in C++
在我的方法中,我希望能够输入一行字符串,它会过滤掉我的第一个单词作为命令,其他单词作为参数。每一行都以"$"开头。
这应该是一个连续的循环,直到我输入"CTR_C"。如果我输入"CTR_C",我应该被问到是否要退出。如果"y"我将退出该方法,如果"n"应该再次出现"$",我可以继续输入我的字符串行。
现在在这一部分,当我输入"n"时,我不会回到我的while(myLoop(循环中,而是被踢出该方法。我忽略了什么错误?
int read_command(char *command, char *parameters[]) { // prompt for user input and read a command line
// getline, extract command and parameters, set noParam, ...
// ...
int noParam = 0;
bool myLoop{true};
string myCommand{};
vector<string> paramVec{};
vector<string> words;
string line;
while (myLoop) {
cout << "$ ";
while (getline(cin, line)) {
int test{};
istringstream iss(line);
string word;
unsigned i = 0;
while (iss >> word) {
if (word != "CTR_C") {
words.push_back(word);
++i;
test++;
} else {
string yn{};
cout << "Do you want to quit (y/n)?" << endl;
cin >> yn;
if (yn == "y") {
myLoop = false;
break;
} else {
if (yn == "n") {
cout << "nicht abbrechen" << endl;
myLoop = true;
test = 999;
} else {
cout << "Eingabe ungueltig" << endl;
myLoop = true;
test = 999;
}
}
}
}
if (test == 0) {
myLoop = false;
break;
} else {
if (test == 999) {
cout << "try again" << endl;
myLoop = true;
} else {
//extract command
myCommand = words.at(0);
cout << "Command is: " << myCommand << endl;
//extract parameters
for (int i = 1; i < words.size(); i++) {
paramVec.push_back(words.at(i));
}
cout << "Param is: ";
for (int i = 0; i < paramVec.size(); i++) {
cout << paramVec.at(i) << endl;
}
}
}
break;
}
}
return (noParam);
};
>您必须在"test == 999"指令之前添加这两行
cin.clear();
cin.ignore(10000, 'n');
您的代码必须如下所示:
if (test == 999) {
cout << "try again" << endl;
myLoop = true;
cin.clear();
cin.ignore(10000, 'n');
}
它现在可以工作了,一个额外的提示使用 else if 这样的语句:
if (test == 0) {
//INSTRUCTION1
}
else if (test == 999) {
//INSTRUCTION2
}
else {
//INSTRUCTION3
}
不像你:
if (test == 0) {
//INSTRUCTION1
}
else {
if (test == 999) {
//INSTRUCTION2
}
else {
//INSTRUCTION3
}
}
相关文章:
- 如何循环打印顶点结构
- 如何在C++中从两个单独的for循环中添加两个数组
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 正在尝试了解输入验证循环
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- 循环后如何继续阅读
- Ardunio UNO解决了多个重叠的定时器循环
- Eigen如何在容器循环中干净地附加矩阵
- 在某些循环内使用vector.push_back时出现分段错误
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- 为什么我的for循环不能正确获取argv
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- while循环中while循环的时间复杂度是多少
- C++中的高效循环缓冲区,它将被传递给C样式数组函数参数
- 为什么在这个代码结束循环中没有得到结束
- 在基于范围的for循环中使用结构化绑定声明
- 用于C++中带有数组和指针的循环
- 循环中的随机函数
- 是什么阻止DOMTimerCoordinator::NextID进入无休止的循环
- 在循环C++中指定字符串之后,不会打印该字符串