提问人:loststudent 提问时间:11/6/2021 更新时间:11/6/2021 访问量:42
如何在没有 EOS 的向量中输入带有 EOS 的数字序列?
How can I enter a sequence of numbers with an EOS in a vector without the EOS in it?
问:
我在向量中输入了双精度的序列,但最后一个数字是 EOS。我怎么不输入停止序列的最后一个数字?
double vec[MAX];
int i = 0;
while(vec[i-1] != EOS){
cin >> vec[i];
i++;
}
答:
0赞
user12002570
11/6/2021
#1
您可以使用以下程序将刚刚读入的序列中的数字添加到 .std::vector
#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;
}
上述程序的输出是(对于如下所示的给定输入):
12 43 78 98 65
elements of the above vector are:
12
43
78
98
评论