C++ 退出c+中的循环+;
我对代码至少有两个问题,但我将从这一个开始 以下代码似乎无法正常工作:C++ 退出c+中的循环+;,c++,for-loop,C++,For Loop,我对代码至少有两个问题,但我将从这一个开始 以下代码似乎无法正常工作: cout<<"Vill du mata in en post till? (ja/nej)"<<endl; //I'm asking if the user wants to run the for-loop one more time or brake with ja(yes) or nej(no). cin>>svar; if (svar == ja) { retur
cout<<"Vill du mata in en post till? (ja/nej)"<<endl; //I'm asking if the user wants to run the for-loop one more time or brake with ja(yes) or nej(no).
cin>>svar;
if (svar == ja)
{
return 0;
}
查看代码,很明显您正在尝试将字符串与名为
ja
的未初始化int进行比较。如果要将svar与返回有意义值的内容进行比较,则需要将字符串与字符串进行比较,即
if(svar==ja”)
而不是if(svar==ja)
我看不到代码中其他地方使用了int“ja”和“nej”。它们的用途是什么?变量
ja
和nej
未初始化。将svar
与它们进行比较是徒劳的。svar应该是一个字符串(因为您希望用户输入字符串“ja”或“nej”,而不是代码期望的整数),考虑到您提出的问题,您可能应该检查“nej”
而不是“ja”
。如果只想退出循环而不想退出函数,请使用break
:
// ...
string svar = "";
for (int i=0; i<10; i++)
{
// ...
cout<<"Vill du mata in en post till? (ja/nej)"<<endl;
cin >> svar;
if (svar == "nej")
{
return 0;
// If you only want to exit the loop and not the function you can use:
// break;
}
}
/。。。
字符串svar=“”;
for(int i=0;ija需要是一个字符串,您需要使用字符串比较函数来检查是否相等。ja未初始化的原因是什么?他的代码声明:bool svar;//behövs för frågan om man vill fortsätta.
谢谢,非常有用。
// ...
string svar = "";
for (int i=0; i<10; i++)
{
// ...
cout<<"Vill du mata in en post till? (ja/nej)"<<endl;
cin >> svar;
if (svar == "nej")
{
return 0;
// If you only want to exit the loop and not the function you can use:
// break;
}
}