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

How do I use CIN to capture two different data types in one line?

本文关键字:两种 数据类型 一行 CIN 何使用      更新时间:2023-10-16

这是一项家庭作业:基本上,我需要使用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循环上迭代?

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

您的tempGrade变量开始时为0

您的循环条件是tempGrade > 0;但是在该点tempGrade仍然为零,因此从不进入循环。在读取后,在循环体内部检查值;或者可能将循环重构为do {} while (tempGrade > 0);

同样,您可能想要检查神奇的tempName值,并在尝试读取其等级之前退出循环

然后您会发现grades[student]是无效的,因为您从未从grades的初始空状态调整其大小。据推测,您已经在实际代码中修复了grades[student][i].push_back(tempGrade);,因为它无法编译。

答案实际上进入CoffeeandCode。

矢量没有初始长度:

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

应该是

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