cin,输入所需详细信息后无输出
cin, no output after entering required details
我是 C++ 的新手,正在尝试在 NetBeans 中创建一个基本程序。下面是我想出的代码:
int main() {
unsigned scores[11] = {};
unsigned grade;
while (cin >> grade){
if (grade <= 100){
++scores[grade/10];
}
}
for(int i = 0; i < 10; i++){
cout << scores[i] << endl;
}
return 0;
}
但是,当我输入一串数字时
2 15 90 99 100
然后按回车,程序还是运行,没有显示结果。为什么会这样?有人可以帮帮我吗?在此先感谢您的帮助!
您需要发送流结束字符,UNIX 下为 ctrl+d,windows 下为 ctrl-z。您还可以重组代码以读取一行(直到换行符)然后解析它:
unsigned scores[11] = {};
unsigned grade;
std::string line;
if (std::getline(cin, line)) {
std::stringstream str(line);
while (str >> grade) {
if (grade <= 100) {
++scores[grade / 10];
}
}
}
for(int i = 0; i < 10; i++){
cout << scores[i] << endl;
}
我是 C++ 的新手,正在尝试在 NetBeans 中创建一个基本程序。下面是我想出的代码:
int main() {
unsigned scores[11] = {};
unsigned grade;
while (cin >> grade){
if (grade <= 100){
++scores[grade/10];
}
}
for(int i = 0; i < 10; i++){
cout << scores[i] << endl;
}
return 0;
}
但是,当我输入一串数字时
2 15 90 99 100
然后按回车,程序还是运行,没有显示结果。为什么会这样?有人可以帮帮我吗?在此先感谢您的帮助!
您需要发送流结束字符,UNIX 下为 ctrl+d,windows 下为 ctrl-z。您还可以重组代码以读取一行(直到换行符)然后解析它:
unsigned scores[11] = {};
unsigned grade;
std::string line;
if (std::getline(cin, line)) {
std::stringstream str(line);
while (str >> grade) {
if (grade <= 100) {
++scores[grade / 10];
}
}
}
for(int i = 0; i < 10; i++){
cout << scores[i] << endl;
}