输入特定字母退出循环,c++

Exit a loop by entering a specific letter, c++

我知道以前有人问过类似的问题,但我的有点不同。

在我在这里找到的问题中,循环应该在用户按下特定字符或数字等之后结束,这样在编写代码时就可以将该字符分配给变量。

例如,当我们在循环中输入非负数 cin>>a; 并且当我们输入负数时循环应该结束我们只写 while(a >=0) 或者如果用户应该输入一些单词,我们将它们保存在变量 A 中,我们写 cin>>A 我们希望循环在他们输入 s 时结束,我们可以简单地写 while( A != 's')

但是我的题比较难

用户应该输入以下变量的值:

char operationcode; int b; int e; 和可选的 int k;

如果 operationcode == 'm' 用户应该输入 k 的值,这样我就可以用 if(operationcode == 'm') {cin>>k} 来处理它 - 对吗?

当用户按下键时循环结束:'e'

我对此有一些想法,但我想确定我是否正确。

第一个是:

int main(){
char operationcode; int b, e, k;
char stop = ' ';

while(stop != 'e')
{
cin>>operationcode>>b>>e;

if(operationcode == 'm') cin>>k;
}

我知道也可以使用 getch() 但我应该只使用 <iostream> 而不是其他。对于 getch() 我需要 #include <conio.h>.

你能告诉我我的想法是否正确吗?

问题出在你的循环上。它会检查您甚至还没有指定的字符 stop

所以,这里正确的做法是

while(stop != 'e')
{
  //Not sure why you need 'em here.
  cin>>operationcode>>b>>e;

  if(operationcode == 'm') cin>>k;

 //assign stop here.
 cin>>stop
}

你应该使用 operationcode != stop 作为 while 循环的条件,否则我不知道循环将如何停止。

此外,如果你使用 do while 循环会更有意义:

int main(){
    char operationcode; int b, e, k;
    char stop = 'x';

    do {
        cin>>operationcode>>b>>e;

        if(operationcode == 'm') cin>>k;

        cout << "code:" << operationcode << "b:" << b << "e:" << e << "k:" << k << endl;
    } while(operationcode != stop);

    return 0;
}

另请注意,由于 cin >> operationcode >> b >> e 将 trim 空格,因此使用空格来检测 stop 并不是一个好主意。我在这里使用了x

因此,现在如果您 运行 该程序,它应该这样做:

1 2 3 4
>> code:1b:2e:3k:0

m 1 2 3 4
>> code:1b:2e:3k:4

x 0 0 0 0
>> code:xb:0e:0k:0