【问题标题】:C++ <iostream> cin don't work properly [closed]C++ <iostream> cin 无法正常工作 [关闭]
【发布时间】:2017-04-25 18:48:15
【问题描述】:
World::World() {
    int width = -1;
    int height = -1;

    cout << "Aby rozpoczac gre wpisz rozmiar planszy" << endl;
    cout << "Aby uruchomic domyslne romiary zostaw pole puste" << endl;

    cout << "Podaj szerokosc: ";
    // I don't see what i'm  typing and i need to press enter twice;
    cin >> width;

    cout << "Podaj wysokosc: ";
    // I don't see what i'm typing too and make my program crash
    cin >> height;

    World(height, width);
}

couts 工作得很好,但 cin 实在是太糟糕了。 在第一次输入时,我看不到我在输入什么,我需要按两次回车; 在 secend cin 时,我也看不到任何东西,当我按任意键时,程序崩溃

【问题讨论】:

  • 您向我们展示的代码应该可以工作。您的问题出在其他地方。
  • 你认为World(height, width); 是做什么的?
  • 我的建议是学习使用调试器。不要急于认为你发现了某种类型的编译器或系统错误。
  • 您真的需要std::endl 需要的额外内容吗? '\n' 结束一行。

标签: c++ input cin cout


【解决方案1】:

线

 World(height, width);

构造一个临时对象并丢弃它。当前对象的成员变量永远不会被正确初始化。

简化您的代码。移动代码以获取输入数据到调用它的函数。例如,在main 中使用它。

int width = -1;
int height = -1;

cout << "Aby rozpoczac gre wpisz rozmiar planszy" << endl;
cout << "Aby uruchomic domyslne romiary zostaw pole puste" << endl;

cout << "Podaj szerokosc: ";
// I don't see what i'm  typing and i need to press enter twice;
cin >> width;

cout << "Podaj wysokosc: ";
// I don't see what i'm typing too and make my program crash
cin >> height;

World w(height, width);

简化默认构造器(将heightMemberwidthMember替换为真正的成员变量):

World::World() : heightMember(0), widthMember(0) {}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-29
    相关资源
    最近更新 更多