如何从输入中获取特定字符

how to get a specific character from input?

本文关键字:字符 获取 输入      更新时间:2023-10-16

我做了一个关于getchar的教程:getChar - C++ 教程

这一切都有效,直到我想进行一些修改。

char c;
puts("enter . to exit");
do{
    c=getchar();
} while (c != '.'); {
    if(c == 's'){
        upgradeOne();
        cout << "upgrade1 is done" << endl;
}
    if (c == 'a'){
        upgradeTwo();
        cout << "upgrade2 is done" << endl;
    }
}
while (total < 999){
    total += i;
    cout << total << endl;
}

我想在用户输入使用特定字符时使用特定方法。如果用户键入 a,则必须激活方法升级二()。我应该怎么做?

输入的重复处理发生在do...while循环中。仅当按下'.'时,循环才会离开。

如果你想对特定的字符做出反应,你必须将你的if(c==...)语句移动到这个循环中(即在getchar()while之间)。

如果你想运行循环直到用户输入 period(.),那么你可以使用一些最初将设置为 true 的布尔标志。然后写一段时间,直到标志为假。在 while 中读取字符,如果是句点,则将标志设置为 false。

或者,您可以无限运行 while 循环,如果 char 是一个句点,则中断循环,否则继续。