为什么这个do-while循环每隔一个循环只写入数组?
Why does this do-while-loop only write to the arrays every other loop?
这个 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++;
};
}
相关文章:
- 我试图制作一个程序,要求用户输入问题和答案,但程序循环不正确
- C++-字符串是否包含一个带有简单循环的单词
- 基于范围的 for 循环:迭代使用一个元素扩展的向量
- 我可以创建一个包含两个变量的 for 循环,但时间复杂度仍然为 O(n) 吗?
- 使用一个循环与两个循环
- 用于在 C++ 中使用 while 循环查找下一个素数的简单函数
- 使用一个 for 循环如何迭代和测试迭代器值?
- 我正在尝试创建一个菜单,但我的代码一直在循环
- 转到基于范围的 for 循环中的下一个迭代器
- C++:返回一个基于范围 for 循环迭代器,其中包含继承对象
- 如何循环 n 次,在 xml 文件中每个循环一个级别
- 初始化时 num 的哪个值会给这个嵌套循环一个"true"输出?
- 两次相同的 for 循环:一个编译,另一个不编译
- 如何在C 中循环一个语句
- 循环一个级数
- 如何在c++中循环一个函数
- 循环一个精灵以显示不止一次
- C++循环一个菜单,直到选择了所有选项
- QT:如何每秒循环一个方法?C++
- 循环一个mpl::map