c++ - 将输入流转换为双向量
问题描述
我在获取逗号分隔数字的输入行以正确传递到双向量时遇到问题。
我对 C++ 还比较陌生,而且有点吃不消。我试过使用双数组,但双向量似乎效果更好。
int main(){
vector<double> vect;
string input1;
string token;
int i;
int size;
cout << "Please input up to 1000 comma-delimited numbers (I.E. '5,4,7.2,5'): ";
cin >> input1;
stringstream ss(input1);
while (ss >> i){
vect.push_back(i);
if (ss.peek() == ','){
ss.ignore();
}
}
for (int j = 0; j < vect.size(); j++){
cout << vect.at(j) << ", ";
}
}
整数似乎可以通过,但如果我包含小数(IE 1.4),则不包含小数。没有错误消息。我怎样才能解决这个问题?
解决方案
您正在使用整数从ss
( int i;
) 中读取。整数不能包含小数点或分数。将其更改为double
,您会没事的。也std::vector
几乎总是比普通数组更可取。
请注意,在最后一个 for 循环中,您还可以使用下标运算符来访问向量元素:
for (int j = 0; j < vect.size(); j++){
cout << vect[j] << ", ";
}
推荐阅读
- excel - 用于在 Excel 中停止 ODBC 刷新的 Excel VBA 代码
- python-3.x - 如何将 df 的列更改为 df 的索引?
- javascript - 将所有依赖项捆绑到一个导入文件中
- themes - 在一个 Grav CMS 网站上拥有两个主题的最佳方式是什么?
- javascript - 使用 Javascript 展平父子 JSON 数组
- python - 仅当一个或多个项目时,我如何使 for 循环工作!='是'
- c# - 当试图从洗好的牌堆中展示一手牌时,它会用梅花 A 填满每一手牌
- java - 如何使用 Apache Poi 在 Excel 中设置/插入文本/值
- visual-studio-2015 - 如何在 VS2015 键盘部分创建或修改复制行的快捷方式?
- css - 为什么css text-align:center,而不是居中文本?相同格式的下划线有效