c++ - c ++输入for循环后跟另一个输入
问题描述
c++ Windows 上的 Microsoft Visual Studio。
我对编码很陌生。目前正在通过Strupstrup的Programming --Principles and Practice Using C++,我遇到了一个困难。我要根据用户输入创建一个带有矢量名称和矢量分数的“分数图表”。我使用for循环来获取输入。现在我要修改程序,以便通过用户的第二次输入,我可以搜索列表并“cout<<”一个人的分数。问题是程序完全忽略了第二个“cin>>”命令。我在网上搜索,找不到这个问题的合理答案。正在终止的 for 循环输入与另一个输入(未循环)语法之间是否存在任何特殊交互:
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
vector<string> name;
vector<int> score;
string temp2;
int i;
for (string temp; cin >> temp >> i;) //input terminated with "Ctrl+Z"
name.push_back(temp), score.push_back(i);
for (int i = 0; i < name.size(); ++i) {
for (int j = i + 1; j < name.size(); ++j) {
if (name[i] == name[j]) {
name[j] = "error";
score[j] = 0;
}
}
}
for (int i = 0; i < name.size(); ++i) {
cout << name[i] << "------" << score[i] << "\n";
}
cout << "name"; //this line shows in the console
cin >> temp2; //but I cannot prompt the user to input again?
return 0;
}
解决方案
CTRL-Z
被解释为“文件结束”,因此对该流的任何后续访问都不会再读入项目。唯一安全的方法是更改程序逻辑,使名称列表以“END”结尾,而不是CTRL-Z
. 然后您可以以保存方式继续。
通常,来自终端的输入会逐行读取,然后进行解析。这使得错误处理更容易。请参阅以下代码遵循这种方法:
#include <sstream>
int main() {
string line;
map<string,int> scoreboard;
cout << "enter name score (type END to finish):" << endl;
while (std::getline(cin, line) && line != "END") {
stringstream ss(line);
string name;
int score;
if (ss >> name >> score) {
scoreboard[name] = score;
} else {
cout << "invalid input. Type END to finish" << endl;
}
}
cout << "enter name:" << endl;
string name;
if (cin >> name) {
auto item = scoreboard.find(name);
if (item != scoreboard.end()){
cout << "score of " << name << ":" << item->second << endl;
}
else {
cout << "no entry for " << name << "." << endl;
}
}
}
推荐阅读
- python - 从python中的按钮调用时无法使用全局变量
- android - OpenCV 使用 Android 应用程序的静态库
- javascript - PassportJS 验证过期的 JWT
- python - Scrapy spider 的 PyCharm 调试配置引发错误
- c - 为什么我的程序没有告诉字符串数组的最后一个字符是 NULL?
- python - 线程缓冲区崩溃
- python - 如何使用电报机器人创建超链接?
- javascript - 有没有办法在浏览器中使用流媒体来打开/关闭视频流?
- java - OneToMany 的问题包括 spring jpa 中的过滤子句
- azure - 在 Azure 应用配置中设置/添加功能标志