2012-11-10 240 views
0

我是C++的初学者,我正在做一个do/while循环练习,我遇到了麻烦,因为它承认条件,更别说它没有正确循环。你们可以给我一个很好的基础:如何解决这样一个简单的问题?我想尝试使用字符串来满足do/while循环的条件。Do/While循环不循环

#include <iostream> 
#include <string> 
#include <sstream> 
using namespace std; 

int main() 
{ 
    double mean = 0; 
    string continuer; 
    do 
    { 
     cout << "Do you want to proceed?" << endl; 
     getline (cin, continuer); 
     cout << "something" << endl; 
     cin >> mean; 
    } 
    while (continuer == "Y" || continuer == "y"); 

    return 0; 
} 
+3

你想要什么来实现的,什么是问题呢? –

+0

getline是否使用double类型? – Sasha

+0

@CodingMash我想创建一个非常简单的while while循环,用户只需输入一个数字,然后询问他们是否想继续。萨沙我只假设它。 – Hayden

回答

1

我从你的问题和评论中收集到的,你想按照用户的意愿迭代循环。

你只是想要一个char变量,像这样。

string input ; 
int number = 0 ; 

do 
{ 
    cout << "Please enter a number" << endl ; 
    cin >> number ; 
    cout << "If you want to continue, Press Y" << endl ; 
    cin >> input ; 

} while (input == "Y" || input == "y") ; 

这个do-while循环将执行至少一次,因为在循环执行结束时检查条件。因此,即使用户第一次询问时没有按Y,该循环也会执行一次。之后,只要条件满足,它就会继续。

了解更多关于do-while循环的信息。

http://www.cplusplus.com/doc/tutorial/control/

+0

有没有办法用字符串做到这一点? – Hayden

+0

你在上面的代码中已经做了正确的操作,并且我也为此编辑了我的代码。 –

+0

当我执行代码时,它会提示您是否要继续。无论我按什么,它只会循环一次。 – Hayden

0

你看到了什么?循环的主体应至少执行一次。这是否发生?

此外,Continuer可以比一个字符长,例如“Y \ n”。为此做测试。

这里是我会做什么:

#include <string> 
#include <sstream> 
using namespace std; 



    int main() 
    { 
     double number = 0; 
     string continuer; 
     int loop = 0 
     do 
     { 

      cout << "Do you want to proceed?" << endl; 
      getline (cin, number); 
      cout << "something" << endl; 
      cin>> mean; 
      getline (cin, continuer); 

      cout << "Your answer was '" << continuer << "'." << endl; 
      loop = strcmp("Y", continuer); 
      if (loop != 0) strcmp("y", continuer); 
      if (loop == 0) cout << "Your choice is to stop." << endl; 
      else cout << "Your choice is to continue." << endl; 
     } while (loop == 0); 
     cout << "Bye" << endl; 
     return 0; 
    } 

要尽可能明确,你可以直到你的语言,你正在使用的算法有足够的信心。更容易看到发生了什么,以及何时运行,很容易删除'cout'线。

+0

我不完全确定你的意思是'循环的主体应该至少执行一次。'你能再详细一点吗? – Hayden

+0

@Hayden,@PapaAtHome说的是'do {'和'}之间的界限,而''在任何情况下都会运行至少一次。 – jlledom

+0

我测试了上面的代码,它说'不能将参数2从'std :: string'转换为'const char *' – Hayden