【问题标题】:std::cin does not accept input, program closes immediatelystd::cin 不接受输入,程序立即关闭
【发布时间】:2014-05-09 17:02:42
【问题描述】:

我尝试使用cin 获取一个字符串作为输入并且它有效,但是当我尝试在字符串之后获取一个int 作为输入时,控制台不会要求它并且程序关闭.这是我的代码:

#include <iostream>
#include <string>
using namespace std;

void main(void)
{ 
string a, b;
int c, d, e;

cout << "Enter two words \n";
cin >> a, b; 
cout << "Enter three int";
cin >> c, d, e;
cout << c*d;
}

这段代码不允许我输入第二个输入,但我可以在程序关闭之前看到第二个输出。

【问题讨论】:

    标签: c++ string input int cin


    【解决方案1】:

    你的代码错了:

    cin >> a, b;
    

    不会给你你所期望的。如果您需要从cin 读取字符串,请使用:

    cin >> a;
    cin >> b;
    

    这同样适用于其他类型。

    还要注意:

    void main( void )
    

    不正确。 main 必须返回int

    int main( void )
    {
        return 0;
    }
    

    【讨论】:

    • 好的,谢谢它的工作!老师说应该用void main(void),不知道为什么。
    • 您也可以使用cin &gt;&gt; a &gt;&gt; b 作为流操作符返回对自己的引用。
    【解决方案2】:

    cin &gt;&gt; a, b; 行使用逗号运算符,从左到右计算不同的表达式。结果和下面的代码一样:

    cin >> a;
    b;
    

    当到达cin &gt;&gt; c, d, e; 行时,类似地评估为:

    cin >> c;
    d;
    e;
    

    结果是,当第二个 cin &gt;&gt; ... 语句被计算时,您输入的第二个单词仍在输入缓冲区中,它无需等待用户的更多输入即可完成。

    【讨论】:

      【解决方案3】:

      这是错误的:

      cin >> a, b; 
      

      应该是:

      cin >> a >> b; 
      

      同样:

      cin >> c, d, e;
      

      应该是:

      cin >> c >> d >> e;
      

      确保您以后启用编译器警告 - 这样编译器可以为您指出许多类似这样的简单错误。当我编译启用警告的原始代码时,我得到:

      $ g++ -Wall junk.cpp
      junk.cpp:5:1: error: 'main' must return 'int'
      void main(void)
      ^~~~
      int
      junk.cpp:13:11: warning: expression result unused [-Wunused-value]
      cin >> c, d, e;
                ^
      junk.cpp:11:11: warning: expression result unused [-Wunused-value]
      cin >> a, b;
                ^
      junk.cpp:13:14: warning: expression result unused [-Wunused-value]
      cin >> c, d, e;
                   ^
      3 warnings and 1 error generated.
      

      由此不难看出cin这两条线有问题,还需要将main的返回类型改为int

      【讨论】:

      • 太棒了 - 确保打开这些警告(并注意它们!)。
      【解决方案4】:

      尝试:

      int main(void)
      { 
      string a, b;
      int c, d, e;
      
      cout << "Enter two words \n";
      cin >> a >> b; 
      cout << "Enter three int";
      cin >> c >> d >> e;
      cout << c*d;
      }
      

      【讨论】:

        猜你喜欢
        • 2016-12-14
        • 2017-01-31
        • 2021-01-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多