为什么这个do-while循环每隔一个循环只写入数组?

Why does this do-while-loop only write to the arrays every other loop?

本文关键字:循环 一个 数组 do-while 为什么      更新时间:2023-10-16

这个 do while 循环的目的是将坐标(或点(输入到两个数组中:points_x[] 和 points_y[]。循环是在用户输入非整数输入时停止的。出于某种原因,只有每隔一个 cin 实际写入数组。有谁知道为什么?

cout << "Enter a list of points(x y): ";
do
{
cin >> points_x[v];
cout << points_x[v];
cin >> points_y[v];
cout << points_x[v];
howMany++;
v++;
} while (cin >> points_x[v] && cin >> points_y[v]);

在这里你正在阅读两次(每个坐标一次,x 和 y(

cin >> points_x[v];
cout << points_x[v];
cin >> points_y[v];
cout << points_x[v];

我假设你的意思是"一辛"。

然后,增加将结果写入数组时使用的索引。

v++;

然后,在评估循环条件的同时,再次读取每个坐标:

while (cin >> points_x[v] && cin >> points_y[v])

我假设你的意思是第二个"cin"。

条件期间的读数(即第二个"cin"(已经写入下一个索引,
但正文内部的读数随后再次写入同一索引(覆盖条件读取的值(。

所以最后你输入每个xy两次,一次在条件期间被忽略,一次在循环体内"存活"。

由于输入可以是多个数字,因此最好以字符串形式输入,检查每个数字是否为数字,并在转换为整数后分配。请参阅片段:

bool IsAlpha(string s) {    
for (const auto& c : s)
if (isalpha(c)) return true;
return false;
}
void main()
{     
string str;
cout << "Enter a list of points(x y):";
while(true)
{
cout << "n Enter X ";
cin >> str;
if (IsAlpha(str)) break;
points_x[v] = std::stoi(str);
cout << "  " << points_x[v] ;
cout << "n Enter Y ";
cin >> str;
if (IsAlpha(str)) break;
points_y[v] = std::stoi(str);
cout << points_y[v] << "  ";
howMany++; 
v++;
};
}