c++值在循环后丢失值
c++ value losing value after loop
在编译和执行以下代码时,我有以下问题:在while循环中,x1保持它的值。一旦输入"ok"并且while循环结束,x1将失去其值并重置为0。
你能告诉我是什么原因引起的吗?
p。我知道向量和表,但不使用它们。使用dev c++编译
int main(){
int x1 = 10; int x2=10,x3=10;
int y1=60,y2=20,y3=20;
string res="";
cout << "config x pos ";
cin >> res;
while(res != "ok"){
cin >> res;
x1= atoi(res.c_str());
moveTo(x1, y1);
cout << endl;
}
cout << x1;
cout << "config y pos ";
cin >> res;
while(res != "ok"){
cin >> res;
y1= atoi(res.c_str());
moveTo(x1, y1);
cout << endl;
cout << "x " << x1 << endl;
}
}
一旦你输入"ok"并打破循环,函数atoi(res.c_str())返回0到变量x1;
当您从控制台中输入'ok'时,要执行的下一行是
x1 = atoi(res.c_str());
当面对非数字字符串时,atoi返回0,然后将其赋值给x1。因此,当循环结束时,x1将始终为零。
我不知道为什么你在开始时做两次cin >> res
(一次在循环之前,然后作为循环副本的第一行)。将你的循环改为:
while ( (cin >> res) && (res != "ok") )
{
x1= atoi(res.c_str());
moveTo(x1, y1);
}
你可能还想考虑做一些比atoi
更智能的事情,例如,如果他们输入"hello",这个将只移动到0,等等。
相关文章:
- 如何循环打印顶点结构
- 如何在C++中从两个单独的for循环中添加两个数组
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 正在尝试了解输入验证循环
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- 循环后如何继续阅读
- Ardunio UNO解决了多个重叠的定时器循环
- Eigen如何在容器循环中干净地附加矩阵
- 在某些循环内使用vector.push_back时出现分段错误
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- 为什么我的for循环不能正确获取argv
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- while循环中while循环的时间复杂度是多少
- C++中的高效循环缓冲区,它将被传递给C样式数组函数参数
- 为什么在这个代码结束循环中没有得到结束
- 在基于范围的for循环中使用结构化绑定声明
- 用于C++中带有数组和指针的循环
- 循环中的随机函数
- 是什么阻止DOMTimerCoordinator::NextID进入无休止的循环
- 在循环C++中指定字符串之后,不会打印该字符串