如何使用CIN在一行中捕获两种不同的数据类型
How do I use CIN to capture two different data types in one line?
这是一项家庭作业:基本上,我需要使用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);
相关文章:
- 有没有办法提示用户使用哪种数据类型作为模板 c++
- 如何构造可以调用和返回两种不同类型的模板
- 当 c++ 需要一种数据类型并获取另一种数据类型时会发生什么?
- 有没有办法让C++函数采用具有相同成员的两种不同类型?
- 将一种数据类型的向量复制到同一数据类型的结构向量中的有效方法是什么
- 生成一个类Name_class并将两种数据类型存储在一个向量中
- 使用 Arduino 发送两种不同类型的传感器数据
- 如何获得将两种不同类型的相乘的结果类型?
- 尝试连接两种不同类型的结构来创建链表
- 如何获得C - 模板状行为,但仅允许实例化两种特定类型
- 为什么 c++ 编译器在对两种不同类型的数值变量使用"std::max()"函数时会出现错误
- 用于给定描述的哪种数据类型
- 比较C 中的两个数据类型
- 可以使用 std::p air 保存三种数据类型的向量
- 如何使用函数中的模板传递两种不同类型的参数
- 哪种数据类型用于存储文件名和文件大小的使用
- 两种模板类型的sizeof,当两者都是从一个基派生时
- 使用两种数据类型作为参数堆叠STL
- C++如何在一个向量中存储两种数据类型
- 函数定义中使用的两种数据类型to_string(long double _Val)