【问题标题】:How to enter 'quit' to close progrom如何输入“退出”关闭程序
【发布时间】:2013-10-09 15:35:33
【问题描述】:

我需要通过输入“退出”来关闭程序的帮助

例如。

while(true)
{
  cout << "enter a name" << endl;
  std::getline (std::cin,input);
  if(input =='quit')
  {
    break;
  }
}

它没有爆发或退出,为什么你不能将一个字符串与一个int进行比较?

即: while (input != 'quit')

【问题讨论】:

  • 这是什么语言?
  • can't compare a string to a int... 为什么不能将苹果与橙子进行比较?它们是不同的东西。您可以尝试将您的字符串 convert 转换为 int 并进行比较,反之亦然。
  • 但我还需要将输入作为字符串,因为稍后我将在代码中将其与其他变量进行比较.....有没有办法在不转换为字符串的情况下“退出”程序?
  • 我删除了我的答案,因为您一直在编辑问题,以至于它完全改变了原始问题。请不要那样做。

标签: c++ string quit


【解决方案1】:

quit 需要用双引号括起来才能成为string

#include <iostream>

int main()
{
    std::string input;
    while (true)
    {
        std::cout << "enter a name: ";
        std::getline(std::cin, input);
        if (input == "quit")
        {
            break;
        }
    }
    std::cout << "Broken" << std::endl;
}

See it run.

为什么你不能将stringint 进行比较。

因为 标准未定义此行为。 "1.0" 会等于 1 吗?

【讨论】:

  • 欢迎来到他的问题的第 3 版。希望它不会再次改变使您的答案无效:-)
  • @user2855990 既然你现在已经得到了这个问题的答案,你应该删除旧版本的问题。也不要忘记接受这个答案 - 单击答案旁边的复选标记以接受。
猜你喜欢
  • 2023-04-10
  • 1970-01-01
  • 2018-12-04
  • 2016-04-20
  • 2015-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多