【问题标题】:If-statement wont cout and there are no errors, (according to Xcode [duplicate]If-statement wont cout 并且没有错误,(根据 Xcode [重复]
【发布时间】:2013-07-01 16:34:28
【问题描述】:

一旦程序到达 if 语句,它就会忽略它并停止。 Xcode 说没有错误,所以我不知道发生了什么。

#include <iostream>
#include <string>

int main()
{
    std::string team;
    std::cout << "Welcome to The Baseball game!\n" << std::endl;
    std::cout << "choose a team.\n";
    std::cin >> team;

    if (team == "Arizona Diamondbacks") //this is were it stops working
    {
        std::cout << "You chose the Arizona Diamondbacks, here is your lineup:" << std::endl << "1. RF Gerrardo Parra" << std::endl << "2. 2B Willie Bloomquist" << std::endl << "3. 1B Paul Goldschmidt" << std::endl << "4. C Miguel Montero" << std::endl << "5. LF Jason Kubel" << std::endl << "6. CF A.J. Pollock" << std::endl << "7. SS Didi Gregorius" << std::endl << "8. 3B Cliff Pennington" << std::endl << "9. SP Patrick Corbin" << std::endl << "your starting pitcher will be Patrick Corbin.\n";
    }
    if (team == "Atlanta Braves")
    {
        std::cout << "you chose the Atlanta Braves";
    }
    return 0;
}

【问题讨论】:

  • 你为什么说它停止工作?什么“停止”?在我看来它会正常返回。
  • cout 不是动词。
  • @femtoRgon 不,这是不同的。 teamstd::string
  • 我错了,谢谢@hvd。
  • 你自己有没有努力解决这个问题?你有没有“std::cout

标签: c++ if-statement


【解决方案1】:
std::cin >> team;

这读一个词。如果您输入“Arizona Diamondbacks”,team 将设置为 "Arizona"。您可以改用getline 来读取整行输入:

std::getline(std::cin, team);

【讨论】:

    【解决方案2】:

    std::stringifstream 提取运算符 &gt;&gt; 提取以空格分隔的字符串。所以你的cin &gt;&gt; team 停在用户输入的第一个空格/制表符处。您需要使用一个读取整行的函数。

    【讨论】:

      【解决方案3】:

      我认为您用于获取字符串输入的cin &gt;&gt; team; 存在问题。尝试使用 getline

      cin 在出现空格字符时停止输入。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-13
        • 2017-10-30
        • 1970-01-01
        • 2019-04-03
        • 1970-01-01
        • 1970-01-01
        • 2017-09-20
        • 2016-04-16
        相关资源
        最近更新 更多