我知道之前已经提出了类似的问题,但我的情况有点不同。
在我在这里找到的问题中,循环应该在使用后按下特定字符或数字等结束,以便在编写代码时能够将该字符分配给变量。
例如,当我们在循环中输入非负数cin>>a;
时,循环应该在我们输入否定时结束,我们只写while(a >=0)
或者如果用户应该输入一些单词,我们将它们保存在变量A中,我们写cin>>A
,我们希望循环在输入s
时结束我们可以简单地写while( A != 's')
但我的问题更难。
用户应输入以下变量的值:
char operationcode; int b; int e;
和可选int k;
用户应该输入k
operationcode == 'm'
的值,以便我可以使用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>
。
你能告诉我我的想法是否正确吗?
答案 0 :(得分:1)
您应该使用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
会修剪空格,因此使用空格检测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
答案 1 :(得分:0)
问题在于你的循环。它会检查您尚未分配的字符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
}