我在向量中输入一组双精度数,但最后一个数字是EOS。我怎么不输入停止序列最后一个数字呢?
double vec[MAX];
int i = 0;
while(vec[i-1] != EOS){
cin >> vec[i];
i++;
}发布于 2021-11-05 16:56:06
您可以使用以下program将刚刚读取的序列中的数字添加到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;
}以上程序的output为(对于如下所示的给定输入):
12 43 78 98 65
elements of the above vector are:
12
43
78
98https://stackoverflow.com/questions/69856426
复制相似问题