New to c++! please help with loop!?

For everyone, just starting with C++ or programming at all. Ask newbie questions in this forum!

Moderators: Darobat, RecursiveS, Dante Shamest, Bugdude, Wizard

New to c++! please help with loop!?

Postby gierkej » Tue Feb 22, 2011 9:19 pm

I need to make this program go back to entering your name when you hit "n" or "N", but continue if you hit "y" or "Y"
Help please??


#include <iostream>
#include <string>
#include <cmath>
#include <cstdlib>

using namespace std;

int main()
{

char name[20];

cout <<"Enter your name:" << endl;
cin.getline(name, 20);
cout <<"\nYou have chosen the name: " << name << endl;

cout <<"\nIs this correct?\n<Y/N>\n" << endl;

char yn;
cin >> yn;


if (yn == 'y' || yn == 'Y')
cout <<"\nThen let's move on...\n" << endl;//continue program if user enters "Y or y"

else if (yn == 'n' || yn == 'N')
cout <<"\nWell then, what is it?\n" << endl;//loop back to start if user enters "N" or "n"


system("pause");
return 0;
}
gierkej
 
Posts: 1
Joined: Tue Feb 22, 2011 9:14 pm

Re: New to c++! please help with loop!?

Postby ventsyv » Thu Feb 24, 2011 2:18 pm

Use a while or do-while loop:

Code: Select all

do
{
   string name; //strings are better because they are not size limited. U'll need to include <string>
   cout <<"Enter your name > ";
   cin>>name; //Now you are not limited to 20 characters
 
   cout <<"\nYou have chosen the name: " << name << endl;
   cout <<"\nIs this correct?\n<Y/N>\n" << endl;

   char yn;
   cin >> yn;
   
   if (yn == 'N' || yn == 'n')
      cout<<"\nOK, let's try again"<<endl;
   else
      cout<<"Thank you"<<endl;
}
while (yn == 'N' || yn == 'n');
User avatar
ventsyv
 
Posts: 2810
Joined: Mon Sep 22, 2003 5:25 pm
Location: MD USA

Re: New to c++! please help with loop!?

Postby ventsyv » Thu Feb 24, 2011 2:44 pm

Also, please use [code] [/code] or [syntax="cpp"] [/syntax] around your code to keep it readable.
User avatar
ventsyv
 
Posts: 2810
Joined: Mon Sep 22, 2003 5:25 pm
Location: MD USA


Return to For Beginners

Who is online

Users browsing this forum: Google [Bot] and 1 guest

cron