1

下面是我的代码:

char name;
bool isValid = true;
int mode;

cout << "Enter name:" << endl;
cin >> name;

do
{
cout << "Choose a mode" << endl;
cin >> mode;

switch (mode)
{
case 1:
    iniCharacter (name, 110, 100, 100);
    break;
case 2:
    iniCharacter (name, 100, 110, 100);
    break;
case 3:
    iniCharacter (name, 100, 100, 110);
    break;
default:
    isValid = false;
    cout << "Invalid mode, ";
    break;
}
}while (!isValid);

但是当我运行上面的代码时,输​​出如下:

[output]Please enter name:

[input] test

[output] Invalid mode

[output] Invalid mode

[output] Invalid mode

[output] Invalid mode

[output] Invalid mode


...

为什么即使我没有开始向模式输入值,代码也会导致循环?

程序不应该等待用户输入“模式”吗?

4

5 回答 5

1

您可能需要isValid在循环顶部设置为 true 以说明在尝试失败后输入有效输入时的情况:

isValid = true;
于 2013-03-29T14:11:04.247 回答
1

将“名称”的类型更改为“字符串”

于 2013-03-29T14:11:16.993 回答
0

非常简单

只需将名称声明更改为

char name[10]  // assuming your name would be 10 characters long.

整个程序将运行得很好。

希望能帮助到你。

于 2013-03-29T14:20:22.827 回答
0

它留\n在缓冲区中循环while(cin.get()!='\n'); 前尝试do

于 2013-03-29T14:24:26.300 回答
0

使用下面的代码将起作用-

char name[100] = {0};
bool isValid = true;
int mode;

cout << "Enter name:" << endl;
cin >> name;

do
{
cout << "Choose a mode" << endl;
cin >> mode;

switch (mode)
{
case 1:
    iniCharacter (name, 110, 100, 100);
    break;
case 2:
    iniCharacter (name, 100, 110, 100);
    break;
case 3:
    iniCharacter (name, 100, 100, 110);
    break;
default:
    isValid = false;
    cout << "Invalid mode, ";
    break;
}
}while (!isValid);

原因:

  • Since you declared the name as single char and user enter more than single character i.e. "test", first char is assigned to name and rest are placed in the buffer as it is and because those are not integers cin doesn't care to ask you at console. Hence that int i.e. mode will have its initial garbage value only.

  • Also second output was however displayed i.e."Choose a mode" but your console buffer was flooded with that error and hence you were not able to see even that too.

于 2013-03-29T15:47:38.557 回答