C++ <iostream> cin 无法正常工作
C++ <iostream> cin don't work properly
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 太麻烦了。
虽然第一个 cin 我看不到我在输入什么,但我需要按两次回车键;
虽然 secend cin 我也没有看到任何东西,但当我按下任意键时,程序崩溃
行
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);
简化默认构造函数(将heightMember
和widthMember
替换为真正的成员变量):
World::World() : heightMember(0), widthMember(0) {}
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 太麻烦了。 虽然第一个 cin 我看不到我在输入什么,但我需要按两次回车键; 虽然 secend cin 我也没有看到任何东西,但当我按下任意键时,程序崩溃
行
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);
简化默认构造函数(将heightMember
和widthMember
替换为真正的成员变量):
World::World() : heightMember(0), widthMember(0) {}