【问题标题】:how to get a specific character from input?如何从输入中获取特定字符?
【发布时间】:2016-02-08 12:59:31
【问题描述】:

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

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

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;
}

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

【问题讨论】:

  • 你不能跳出 do/while 循环。它总是在寻找一个时期。
  • 我不知道你想做什么,所以我帮不了你。
  • 再一次,如果 OP 正确缩进其代码,解决方案将是微不足道的。
  • 我认为你误解了 do-while 循环的主体在哪里。

标签: c++ visual-c++ char getchar


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    或者您可以无限运行 while 循环,如果 char 是句点则中断循环 else continue。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-20
      • 1970-01-01
      • 2017-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多