首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在向量中输入包含EOS但没有EOS的数字序列?

如何在向量中输入包含EOS但没有EOS的数字序列?
EN

Stack Overflow用户
提问于 2021-11-05 16:33:42
回答 1查看 20关注 0票数 0

我在向量中输入一组双精度数,但最后一个数字是EOS。我怎么不输入停止序列最后一个数字呢?

代码语言:javascript
复制
double vec[MAX];
int i = 0;
    while(vec[i-1] !=  EOS){
        cin >> vec[i];
        i++;
    }
EN

回答 1

Stack Overflow用户

发布于 2021-11-05 16:56:06

您可以使用以下program将刚刚读取的序列中的数字添加到std::vector中。

代码语言:javascript
复制
#include <iostream>
#include <sstream>
#include <vector>
int main()
{
   std::vector<double> vec; //or you can create the vector of a particular size using std::vector<double> vec(size);
   
   double EOS = 65; //lets say this is the EOS
   std::string sequence; //or you can use std::string sequence = "12 43 76 87 65";
   std::getline(std::cin, sequence);//read the sequence of numbers
   
   std::istringstream ss(sequence);
   double temp;
   while((ss >> temp) && (temp!=EOS))
   {
       vec.push_back(temp);
   }
   
   std::cout<<"elements of the above vector are: "<<std::endl;
   //lets print out the elements of the vector 
   for(const double &elem: vec)
   {
       std::cout<<elem<<std::endl;
   }
    return 0;
}

以上程序的output为(对于如下所示的给定输入):

代码语言:javascript
复制
12 43 78 98 65
elements of the above vector are: 
12
43
78
98
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69856426

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档