如何使用CIN在一行中捕获两种不同的数据类型?

时间:2014-04-29 07:10:38

标签: c++ stdvector cin

这是一项家庭作业:基本上,我需要使用cin行捕获一行,如: mary_smith 10 9 10 3 100 8 7.5 10 73 9 10 5 9 87 -1

...然后将名称放在字符串向量中,并将数字(等级)放在具有相同索引的多维向量中。

到目前为止,我有这个:

#include <iostream>
#include <stdlib.h>
#include <iomanip>
#include <vector> 
#include <string>
using namespace std;

vector<string> names;
vector< vector<float> > grades; //Multidimensional vector for grades
string tempName;
float tempGrade;
int student = 0;

int main(){
    do {
        cin >> tempName; //Get the first entry before whitespace
        names.push_back(tempName); //Push the name into the vector

        //For all the other inputs, put the respective grades at the same base index?
        for (int i = 0; tempGrade > 0; ++i) {
            cin >> tempGrade; //Get all grades until -1
            grades[student][i].push_back(tempGrade);//Add grade to the index.
        }
        ++student;
    } while (tempName != "KEY"); //If you see KEY, kill the program.
    return 0;
}

不幸的是,问题是机器会将所有条目视为string。为什么它不会开始在我的for循环中迭代?

更新
以前我说它需要在多维数组中,但我的意思是矢量。我在上面更新了这个。

3 个答案:

答案 0 :(得分:2)

您的tempGrade变量从0开始

答案 1 :(得分:1)

你的循环条件是tempGrade > 0;但此时tempGrade仍为零,因此永远不会输入循环。 在循环体内读取之后的值;或者可能将循环重构为do {} while (tempGrade > 0);

同样,你可能想要检查魔术tempName值并在尝试读取它的等级之前退出循环。

然后你会发现grades[student]无效,因为你永远不会从最初的空状态调整grades。据推测,您已经在实际代码中修复了grades[student][i].push_back(tempGrade);,因为这不会编译。

答案 2 :(得分:0)

实际上回答了CoffeeandCode。

矢量没有初始长度:

vector<string> names;
vector< vector<float> > grades;

应该是

vector<string> names(1);
vector< vector<float> > grades(1);