while 循环和 getchar()

while loop and getchar()

下面是我为大学课程编写的简单程序。我知道它并没有真正做任何事情,但这只是一门课程的作业。

我不明白的部分是,为什么外循环不起作用?

用户需要按“1”继续,程序退出的任何其他键。

但是,如果用户按“1”并退出,它仍然不会继续。

我尝试在 cin >> repeat 之前添加一个 cin.clear() ,但这不起作用。

我也试过 cin.ignore(),但这似乎也没有帮助。

有什么想法吗?

谢谢

int main()
{
    int repeat = '1';
    stack<char> cstr;
    char c;

    while (repeat == '1')
    {
        cout << "Enter in a name: ";

        while (cin.get(c) && c != '\n')
        {
            cstr.push(c);
        }

        cout << "\n Enter another name? 1 = Continue, any other key to exit the program";
        cin >> repeat;
        repeat = getchar();
   }
}
   cin >> repeat; 

它读取 repeat 为 int。 (1 不等于'1')

repeat = getchar();

它读取特殊字符 '\n' 的 int 代码 - 行尾符号。

你必须使用

char repeat = '1';

或写

int repeat = 1;

并且不使用 getchar()

运行 这个。它会以某种方式解决你的问题 repeat=getchar 使 repeat=10.

 int main()
    {
    char  repeat = '1';
    stack<char> cstr;
    char c;

    while (repeat == '1')
    {
        cout << "Enter in a name: ";
        cin.ignore();
        while (cin.get(c) && c != '\n')
        {
            cstr.push(c);
        }

        cout << "\nEnter another name ? \nPress 1 to Continue : ";
        cin >> repeat;
        cout << endl;
    }
    system("pause");
    }

cin >> repeat是为了从键盘读取一个整数,因为repeat是一个int类型的变量。但是,您正在验证从键盘读取的整数是否等于 49(字符“1”的 ASCII 代码),这不是您想要的。一种解决方案是更换行

int repeat = '1';

int repeat = 1;

并替换

while (repeat == '1')

while (repeat == 1)

因为那时您将从键盘读取的整数与整数 1(而不是 字符“1”)进行比较。此外,在循环结束时,您从键盘读取输入并将其存储在 repeat 中,但随后您立即再次读取输入并将该值 存储在 repeat 中, 替换它以前的值。要解决此问题,请替换行

repeat = getchar();

getchar();

应该就可以了。

您的代码完全没有问题。它对我来说似乎工作正常。

编辑:抱歉,在您删除 getchar 之前它不起作用。忘了说了。找出错误的简单方法是只显示变量 repeat 的值,以查看该值是什么以及出错的地方。

显示您的代码有效的屏幕截图

似乎一切正常。不过,我想对您的程序结构发表评论。对于像这样的小程序,没关系,但最好始终以逻辑方式进行练习。对于像这样的问题,你应该实现 do while 循环而不是 while 循环,这样它就可以在不检查的情况下进入,然后接受用户输入并检查 post 条件。示例如下。

    char  repeat;

    do
    {
        //Your codes in here
    }while (repeat == '1');

除非您的问题指定您使用 while 循环,否则使用此方法更符合逻辑。无论如何希望这有帮助。