首页 > 解决方案 > 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;
}

标签: c++for-loopinput

解决方案


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;
        }
    }


}

推荐阅读