英文:
Why is my code not outputting the first element of my vector, but outputs all the others?
问题
This code asks the user for input values, inserts the values into a vector, and then outputs it, but for some reason does not show the first element, but shows all the others.
这段代码要求用户输入数值,将这些数值插入到一个向量中,然后输出它,但出现了一个问题,它不显示第一个元素,却显示了其他所有元素。
英文:
This code asks the user for input values, inserts the values into a vector and then outputs it, but for some reason does not show the first element, but shows all the others.
It might be something really stupid but I am relevantly new to learning c++ and just trying to refine over vectors but cant seem to get this one.
double x;
vector<double> l;
cout << "Enter a list of numbers: ";
cin >> x;
while (cin >> x) {
l.push_back(x);
}
for (auto i = 0; i < l.size(); ++i) {
cout << l[i] << " ";
}
答案1
得分: 1
以下是翻译好的部分:
变量 x
在 while 循环之前的第一个输入
cin >> x;
while (cin >> x) {
被忽略。
在 while 循环之前删除此语句
cin >> x;
还要注意,在此 for 循环中
for (auto i = 0; i < l.size(); ++i) {
cout << l[i] << " ";
}
变量 i
被定义为有符号类型 int
。然而,通常情况下,有符号类型 int
的对象可能不足以表示向量的大小。因此,最好使用基于范围的 for 循环,如下所示
for ( const auto &item : l ) {
cout << item << " ";
}
英文:
The first input for the variable x
that occurs before the while loop
cin >> x;
while (cin >> x) {
is just ignored.
Remove this statement
cin >> x;
before the while loop.
Also pay attention to that in this for loop
for (auto i = 0; i < l.size(); ++i) {
cout << l[i] << " ";
}
the variable i
is defined as having the signed type int
. However in general objects of the signed type int
can be not large enough to represent sizes of vectors. So it would be better to use range based for loop like
for ( const auto &item : l ) {
cout << item << " ";
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论