-4

I am new to c++. I have given assignment in which i have to calculate grades and ask input from the user. If he enter wrong input i have to start program again. If the user enters correct input i have to process data and again ask if he wants to check for another calculation.I have written this code so far. I don't know how to loop back again in the program if the user enters wrong input and to start program again if it is successful. Please Give me guidance over it. Thanks.

#include <cstdlib>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{   
    //Declaring Variable
    char choice;
    char input;
    //Promptin User to Enter his/her Choice
    cout<<"Enter C or c for Computer Science: \n" ;
    cout<<"Enter S or s for Software Engineering: \n";
    cout<<"Enter T or T for Telecom Engineering: \n";

    cout<<"Select any option from the above Menu: ";
    cin>>input; 



    if (input != 'c' || input != 'C'){

        cout<<"Invalid input! Enter the correct input option again";
    }else if (input != 's' || input != 'S' ){
        cout<<"Invalid input! Enter the correct input option again";
    }else if (input != 't' || input != 'T' ){
        cout<<"Invalid input! Enter the correct input option again";
    }else if (input == 'a' || input == 'A'){

    }





    system("pause");
    return 0;

}
5
  • 2
    What about using a do while() loop? Commented Nov 17, 2016 at 10:10
  • 1
    input would have to be both c and C at the same time (how?) not to satisfy input != 'c' || input != 'C'. Why is it so hard? Commented Nov 17, 2016 at 10:10
  • 1
    @LogicStuff It's almost illogical how hard logic can be to some. :) Commented Nov 17, 2016 at 10:14
  • Stack Overflow is not a chatroom where you get "guidance". It is a Question & Answer site. What is your question? Commented Nov 17, 2016 at 10:17
  • Why the downvotes? The question may be basic and lacking the question form, but it isn't a bad question and it is interesting because almost everyone who starts programming is confronted with this. If anything, it probably can be closed as a duplicate. The "Related" list shows stackoverflow.com/questions/13348800/… but I would advise using that because it has undefined behavior (uninitialized variable) Commented Nov 17, 2016 at 10:24

4 Answers 4

0

You can do it using a simple do while loop:

bool valid_input = false;

do
{
    // Code to read and validate the input...
} while (valid_input == false);

If the input is valid, then you set valid_input to true and the loop will end.


On an unrelated note, if you don't case about upper- or lower-case, use e.g. std::tolower so you only have to compare the letter once. E.g. std::tolower(input) != 'c'.

Sign up to request clarification or add additional context in comments.

Comments

0

Here is the code that will prompt the user for answer as long as the answer is defined withing switch statement. ans is a variable to hold a character either 1 or 0 corresponds to the user's input (defined in switch cases or not). If defined, then ans gets 1 other wise it gets value 0. Do While loop repeats while ans is 1 (defined within switch statement).

    #include <iostream>
    #include <cstdlib> 
    using namespace std;


int main() {

 char input; 
 char ans; //correct answer, incorrect answer


 do {
    cout<<"Enter C or c for Computer Science: \n" ;
    cout<<"Enter S or s for Software Engineering: \n";
    cout<<"Enter T or T for Telecom Engineering: \n";
    cout<<"Select any option from the above Menu: ";
    cin>>input; 
      switch (input){
        case 'S': 
          ans = 1; 
          break; 
        case 's': 
         ans = 1; 
         break;
        case 'C': 
          ans = 1; 
          break;
        case 'c': 
         ans = 1;
         break; 
        case 'T': 
          ans = 1; 
          break; 
        case 't': 
         ans = 1; 
         break;
       default:
      ans = 0; 
}

} while (ans);


 return 0;
 }

1 Comment

You could use std::tolower or have muliple cases per block: case 'S':\ncase 's': ans = 1; break;
0

User input handling is very common and can normally use similar patterns.

Basically, you re-ask for the input. You handle the valid choices and break out of the loop and you show an error when the choice is invalid and let the loop ask the input again.

Remark1: by not using switch-case here, I can break out of the loop immediately. I break immediately to avoid specifying the conditions twice or using flags, that is also why I use a loop without end-condition.

Remark2: std::flush is used to input on the prompt line. It makes sure that the prompt is shown before waiting for input.

char inp = 0;
while (true) {
    std::cout << "Give input (a, b): " << std::flush;
    std::cin >> inp;
    inp = std::tolower(inp);
    if (inp == 'a') {
        std::cout << 'a\n';
        break;
    }
    if (inp == 'b') {
        std::cout << 'b\n';
        break;
    }
    std::cout << "invalid choice (" << inp << ")";
}

The invalid choice handling can be done a bit more generic by this function, but the handling of the valid choices must still be done locally:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

char askInputChoice(const std::string& prompt, const std::vector<char>& valid)
{
    char inp = 0;
    while (true) {
        std::cout << prompt << ": " << std::flush;
        std::cin >> inp;
        inp = std::tolower(inp);
        if (std::find(valid.begin(), valid.end(), inp) != valid.end()) {
            break;
        }
        std::cout << "invalid choice (" << inp << ")\n";
    }
    return inp;
}

int main()
{
    char inp = askInputChoice("Give input (a, b)", std::vector<char>{'a','b'});
    switch (inp) {
    case 'a':
        std::cout << "a\n";
        break;
    case 'b':
        std::cout << "b\n";
        break;
    }
}

To restart the program, put it in a while loop, add a choice to quit ('q') and break when that choice is given.

Comments

0

Thanks Guys for All Your Support. Actually it is my First Program in C++ and sorry i have used the word guidance. Actually i have compiled it successfully. Kindly Check my program i know u do not need to but i want to know if i can add more into it to improve it.

#include <cstdlib>
#include <iostream>
#include <conio.h>

using namespace std;

int main(int argc, char *argv[])
{   
    //Declaring Variable
    char choice;
    char input;
    int addTest = 0, matricMarks = 0 , interMarks = 0 , result = 0;
    start: //Label
    system("cls"); // Clear the Screen


    //Prompting User to Enter his/her Choice
    cout<<"Please Select the Degree Programme in which you are interested in to take Addmission: ";
    cout<<"\nEnter C or c for Computer Science: "<<endl ;
    cout<<"Enter S or s for Software Engineering: "<<endl;
    cout<<"Enter T or t for Telecom Engineering: \n"<<endl;

    cout<<"\nSelect any option from the above Menu: ";
    cin>>input; 

    //Switch Statement Started
    switch(input){
        //Case C Started
        case 'c':
        case 'C':

                {
                    cout<<"Enter your Marks in Addmission Test: ";
                    cin>>addTest;
                    cout<<"Enter your Marks in Matric Degree: ";
                    cin>>matricMarks;
                    cout<<"Enter your Marks in Intermediate Degree: ";
                    cin>>interMarks;

                    result = (addTest * 0.20)+(matricMarks * 0.30)+(interMarks * 0.50);

                    if (result >= 70)
                    {
                        cout<<"\nCongratulations! You are eligible for the Computer Science degree program :)"<<endl;

                    }  
                    else
                    {
                        cout<<"Sorry you Do not qualify for Computer Science Degree Programme: "<<endl;
                        system("pause");
                    }
                    break;
                }//Case C Closeed

    //Case s Started
        case 's':
        case 'S':
            {
                    cout<<"Enter your Marks in Addmission Test: ";
                    cin>>addTest;
                    cout<<"Enter your Marks in Matric Degree: ";
                    cin>>matricMarks;
                    cout<<"Enter your Marks in Intermediate Degree: ";
                    cin>>interMarks;

                    result = (addTest * 0.20)+(matricMarks * 0.30)+(interMarks * 0.50);

                    if (result >= 85)
                    {
                        cout<<"\nCongratulations! You are eligible for the Software Enginnering degree program :)"<<endl;

                    }  
                    else
                    {
                        cout<<"\nSorry! you Do not Qualify for Software Engineering Degree: "<<endl;
                        system("pause");
                    }
                    break;

            }//Case S Closed

    //Case t Started
        case 't':
        case 'T':
            {       
                    cout<<"Enter your Marks in Addmission Test: ";
                    cin>>addTest;
                    cout<<"Enter your Marks in Matric Degree: ";
                    cin>>matricMarks;
                    cout<<"Enter your Marks in Intermediate Degree: ";
                    cin>>interMarks;

                    result = (addTest * 0.20)+(matricMarks * 0.30)+(interMarks * 0.50);

                    if (result >= 80)
                    {
                        cout<<"\nCongratulations! You are eligible for the Telecom Engineering degree program :)"<<endl;

                    }  
                    else
                    {
                        cout<<"Sorry you Do not Qualify for Telecom Enginnering Degree Programme: "<<endl;
                        system("pause");
                    }
                    break;
            }//Case t Closed

    //Default Case Started

        default:
            {
                   cout<<"\nInvalid input! Enter the correct option again: \n";
                    system("pause");   
                    goto start;                   //Jump To Label Start      
            }//Deafult Case Closed

    }// Switch Statement Close

    //do while Loop Started
    do{

        cout<<"\nDo you want to check your eligibility in some other degree program y/n? : ";
        cin>>choice;
        if (choice=='Y'||choice=='y')
         {
          goto start;                                   //jump to Label start:
         }
        else if (choice=='N'||choice=='n')
         { 
           break;
         }
        }while(choice  == 'y' || choice == 'Y');
    //Do while Loop Closed





    system("pause");
    return 0;

}

3 Comments

Nice to see some feedback. It unfortunately isn't done enough. However, the more common way of giving feedback is by up- or downvoting, accepting and commenting on the question/answer (upvoting is also a way of encouraging the people to continue helping you). for code review, I direct you to codereview.stackexchange.com. Mind you that they also have rules and conventions.
I did notice that in spite of all answers suggesting to you a while loop, you used a goto. Goto's may have there use and in your exercise, it is still simple. However (over)using goto's can become problematic rather quickly and I hope you won't get into difficulties with them the night you have to finish your assignment. They are almost never used anymore because a combination of 3 goto's can already be very difficult to follow.
In this case the goto start can be replaced by a bool restart = true; do {...} while (restart) loop and restart = false; in the choice == 'n' branch (also notice that the validity check of your restart question is wrong: check it with a debugger and some different input)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.