goobergoober
goobergoober

Reputation: 9

Loop until a specific char is entered (C++)

I have a small problem here. This portion of code does not break the loop when the condition has been met. It is supposed to skip the loop if the user enters 'N', and to break if the user enters 'N' after each new loop prompt. Otherwise, it is the indefinitely loop with each input of 'Y'.

#include <iostream>
using namespace std;

void text();
char text()
{
    char choice;
    cout << "Enter Y/N: " << endl;
    cin >> choice;
    return choice;
}

int main()
{
     text();
     while(text() == 'Y' || text() == 'y') 
     {
         text();
         if(text() == 'N' || text() == 'n') {break;}
     }
system("pause");
return 0;
}

Upvotes: 0

Views: 1019

Answers (3)

Omranovic
Omranovic

Reputation: 43

Simply save the entered char in a char variable

char e = text();
   while(e== 'Y' || e== 'y') 
 {
     choice = text();
     if(e== 'N' || e== 'n') 
        break;
 }

Also erase the: void text(); You can't have two functions with the same name or one might say, can not overload functions distinguished by return type alone.

Upvotes: 0

Ron
Ron

Reputation: 15501

The following will suffice:

#include <iostream>
int main(){
    char choice = 'y';
    while (std::cin && ::tolower(choice) == 'y'){
        // do work
        std::cout << "Enter Y/N: ";
        std::cin >> choice;
    }
}

If you insist on using a function then a simple void function with an argument passed by reference will do:

#include <iostream>
void choicefn(char& c){
    std::cout << "Enter Y/N: " << std::endl;
    std::cin >> c;
}
int main(){
    char choice = 'y';
    while (std::cin && ::tolower(choice) == 'y'){
        // do work
        choicefn(choice);
    }
}

If you want to be really pedantic then modify the while statement to:

while (std::cin && ::tolower(choice) == 'y' && ::tolower(choice) != 'n')

Upvotes: 0

Hatik
Hatik

Reputation: 1159

The problem with the code is that you run text() function in every check, asking for input, the solution would be to store the result from text() into another variable like below:

#include <iostream>
using namespace std;

void text();
char text()
{
    char choice;
    cout << "Enter Y/N: " << endl;
    cin >> choice;
    return choice;
}

int main()
{
     char choice;
     choice = text();
     while(choice == 'Y' || choice == 'y') 
     {
         choice = text();
         if(choice == 'N' || choice == 'n') {break;}
     }
system("pause");
return 0;
}

Upvotes: 1

Related Questions