我的代码为什么没有输出向量的第一个元素,而输出了所有其他元素?

huangapple go评论54阅读模式
英文:

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 &gt;&gt; x;
while (cin &gt;&gt; x) {

is just ignored.

Remove this statement

cin &gt;&gt; x;

before the while loop.

Also pay attention to that in this for loop

for (auto i = 0; i &lt; l.size(); ++i) {
    cout &lt;&lt; l[i] &lt;&lt; &quot; &quot;;
}

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 &amp;item : l ) {
    cout &lt;&lt; item &lt;&lt; &quot; &quot;;
}

huangapple
  • 本文由 发表于 2023年7月4日 22:44:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/76613762.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定