Validate input and ask again if invalid












1














In this code I have several querys for user input. If there is an invalid input like 'r' instead of 4, I want my programm to say "invalid input" and ask for another user input. I tried a lot but I couldn't get it to work.
I commented the problematic locations in the code. Thanks for help.



#include <stdio.h>

int main()
{
double Operand1;
double Operand2;
int Menuchoice;
int Input;
char Dummy;
double Result;

do
{

printf("Simple Calculatorn");
printf("========================n");
printf("n");
printf("1. Additionn");
printf("2. Subractionn");
printf("3. Multiplicationn");
printf("4. Divisionn");
printf("9. Quitn");


Input = scanf("%i", &Menuchoice); // At this point I want to check if there is a valid input and
do scanf("%c", &Dummy); // if not the programm should ask again
while (Dummy != 'n');

if(Input)
{
switch(Menuchoice)
{
case 1: printf("Type in the first operand:n");
scanf("%lf", &Operand1) // Here I want to validate the input
printf("Type in the second operand:n"); // again and the programm should also ask
scanf("%lf", &Operand2) // again if it was invalid
printf("%lf + %lf = %lfn", Operand1, Operand2, Result);
break;
case 2:
case 3:
case 4:
default: printf("No valid input!n");
break;
}
}

}while (Menuchoice != 9);

return 0;
}









share|improve this question
























  • First rule of user input: Don't use scanf.
    – melpomene
    Nov 22 at 22:23










  • Well we have to use it at this stage of our studies.
    – Ray Ban
    Nov 22 at 22:27
















1














In this code I have several querys for user input. If there is an invalid input like 'r' instead of 4, I want my programm to say "invalid input" and ask for another user input. I tried a lot but I couldn't get it to work.
I commented the problematic locations in the code. Thanks for help.



#include <stdio.h>

int main()
{
double Operand1;
double Operand2;
int Menuchoice;
int Input;
char Dummy;
double Result;

do
{

printf("Simple Calculatorn");
printf("========================n");
printf("n");
printf("1. Additionn");
printf("2. Subractionn");
printf("3. Multiplicationn");
printf("4. Divisionn");
printf("9. Quitn");


Input = scanf("%i", &Menuchoice); // At this point I want to check if there is a valid input and
do scanf("%c", &Dummy); // if not the programm should ask again
while (Dummy != 'n');

if(Input)
{
switch(Menuchoice)
{
case 1: printf("Type in the first operand:n");
scanf("%lf", &Operand1) // Here I want to validate the input
printf("Type in the second operand:n"); // again and the programm should also ask
scanf("%lf", &Operand2) // again if it was invalid
printf("%lf + %lf = %lfn", Operand1, Operand2, Result);
break;
case 2:
case 3:
case 4:
default: printf("No valid input!n");
break;
}
}

}while (Menuchoice != 9);

return 0;
}









share|improve this question
























  • First rule of user input: Don't use scanf.
    – melpomene
    Nov 22 at 22:23










  • Well we have to use it at this stage of our studies.
    – Ray Ban
    Nov 22 at 22:27














1












1








1







In this code I have several querys for user input. If there is an invalid input like 'r' instead of 4, I want my programm to say "invalid input" and ask for another user input. I tried a lot but I couldn't get it to work.
I commented the problematic locations in the code. Thanks for help.



#include <stdio.h>

int main()
{
double Operand1;
double Operand2;
int Menuchoice;
int Input;
char Dummy;
double Result;

do
{

printf("Simple Calculatorn");
printf("========================n");
printf("n");
printf("1. Additionn");
printf("2. Subractionn");
printf("3. Multiplicationn");
printf("4. Divisionn");
printf("9. Quitn");


Input = scanf("%i", &Menuchoice); // At this point I want to check if there is a valid input and
do scanf("%c", &Dummy); // if not the programm should ask again
while (Dummy != 'n');

if(Input)
{
switch(Menuchoice)
{
case 1: printf("Type in the first operand:n");
scanf("%lf", &Operand1) // Here I want to validate the input
printf("Type in the second operand:n"); // again and the programm should also ask
scanf("%lf", &Operand2) // again if it was invalid
printf("%lf + %lf = %lfn", Operand1, Operand2, Result);
break;
case 2:
case 3:
case 4:
default: printf("No valid input!n");
break;
}
}

}while (Menuchoice != 9);

return 0;
}









share|improve this question















In this code I have several querys for user input. If there is an invalid input like 'r' instead of 4, I want my programm to say "invalid input" and ask for another user input. I tried a lot but I couldn't get it to work.
I commented the problematic locations in the code. Thanks for help.



#include <stdio.h>

int main()
{
double Operand1;
double Operand2;
int Menuchoice;
int Input;
char Dummy;
double Result;

do
{

printf("Simple Calculatorn");
printf("========================n");
printf("n");
printf("1. Additionn");
printf("2. Subractionn");
printf("3. Multiplicationn");
printf("4. Divisionn");
printf("9. Quitn");


Input = scanf("%i", &Menuchoice); // At this point I want to check if there is a valid input and
do scanf("%c", &Dummy); // if not the programm should ask again
while (Dummy != 'n');

if(Input)
{
switch(Menuchoice)
{
case 1: printf("Type in the first operand:n");
scanf("%lf", &Operand1) // Here I want to validate the input
printf("Type in the second operand:n"); // again and the programm should also ask
scanf("%lf", &Operand2) // again if it was invalid
printf("%lf + %lf = %lfn", Operand1, Operand2, Result);
break;
case 2:
case 3:
case 4:
default: printf("No valid input!n");
break;
}
}

}while (Menuchoice != 9);

return 0;
}






c loops validation






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 22 at 22:26

























asked Nov 22 at 22:16









Ray Ban

326




326












  • First rule of user input: Don't use scanf.
    – melpomene
    Nov 22 at 22:23










  • Well we have to use it at this stage of our studies.
    – Ray Ban
    Nov 22 at 22:27


















  • First rule of user input: Don't use scanf.
    – melpomene
    Nov 22 at 22:23










  • Well we have to use it at this stage of our studies.
    – Ray Ban
    Nov 22 at 22:27
















First rule of user input: Don't use scanf.
– melpomene
Nov 22 at 22:23




First rule of user input: Don't use scanf.
– melpomene
Nov 22 at 22:23












Well we have to use it at this stage of our studies.
– Ray Ban
Nov 22 at 22:27




Well we have to use it at this stage of our studies.
– Ray Ban
Nov 22 at 22:27












1 Answer
1






active

oldest

votes


















2














Manual page of scanf:




On success, these functions return the number of input items successfully matched and assigned; this can be fewer than provided for, or even zero, in the event of an early matching failure.




So here is a sample which could lead you to solve your problem:



#include <stdio.h>

int main (int argc, char* argv)
{
double o;
int res;

// To illustrate, I chose to set up an infinite loop.
// If the input is correct, we'll "break" it
while(1)
{
printf("Enter a double: ");
res = scanf("%lf",&o);

// Success = 1 read input
if (res == 1)
{
printf("Yahoo, got it right: %fn",o);
break; // We exit the loop
}

// Ah, we failed
printf("Please retry.n");
// popping the CR character to avoid it to be got by the next scanf()
getchar();

// Here we go for another loop.
}

// Good, we got our double.
printf("Hey, sounds like we got outside this infinite loop.n");
}


Example:



user@so:~$ ./a.out 
Enter a double: r
Please retry.
Enter a double: f
Please retry.
Enter a double: 6.543
Yahoo, got it right: 6.543000


Keep in mind this check is not perfect. For example, "frg6sgg" will success and be displayed as 6.0000000 by printf().






share|improve this answer























  • Why does the if case only check if "res" is 1? Sorry I really don't understand this..
    – Ray Ban
    Nov 22 at 23:09










  • When I do it like this: while(1) { printf("Type in your first operand:n"); Input = scanf("%lf", &Operand1); if (Input == 1) break; printf("No valid inputn"); } I get an infinite loop, why?
    – Ray Ban
    Nov 22 at 23:25












  • Understood now :) Got it working. I did not understand the quote of the manual page but your explanation was way better. Thanks a lot sir.
    – Ray Ban
    Nov 22 at 23:58











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53438567%2fvalidate-input-and-ask-again-if-invalid%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









2














Manual page of scanf:




On success, these functions return the number of input items successfully matched and assigned; this can be fewer than provided for, or even zero, in the event of an early matching failure.




So here is a sample which could lead you to solve your problem:



#include <stdio.h>

int main (int argc, char* argv)
{
double o;
int res;

// To illustrate, I chose to set up an infinite loop.
// If the input is correct, we'll "break" it
while(1)
{
printf("Enter a double: ");
res = scanf("%lf",&o);

// Success = 1 read input
if (res == 1)
{
printf("Yahoo, got it right: %fn",o);
break; // We exit the loop
}

// Ah, we failed
printf("Please retry.n");
// popping the CR character to avoid it to be got by the next scanf()
getchar();

// Here we go for another loop.
}

// Good, we got our double.
printf("Hey, sounds like we got outside this infinite loop.n");
}


Example:



user@so:~$ ./a.out 
Enter a double: r
Please retry.
Enter a double: f
Please retry.
Enter a double: 6.543
Yahoo, got it right: 6.543000


Keep in mind this check is not perfect. For example, "frg6sgg" will success and be displayed as 6.0000000 by printf().






share|improve this answer























  • Why does the if case only check if "res" is 1? Sorry I really don't understand this..
    – Ray Ban
    Nov 22 at 23:09










  • When I do it like this: while(1) { printf("Type in your first operand:n"); Input = scanf("%lf", &Operand1); if (Input == 1) break; printf("No valid inputn"); } I get an infinite loop, why?
    – Ray Ban
    Nov 22 at 23:25












  • Understood now :) Got it working. I did not understand the quote of the manual page but your explanation was way better. Thanks a lot sir.
    – Ray Ban
    Nov 22 at 23:58
















2














Manual page of scanf:




On success, these functions return the number of input items successfully matched and assigned; this can be fewer than provided for, or even zero, in the event of an early matching failure.




So here is a sample which could lead you to solve your problem:



#include <stdio.h>

int main (int argc, char* argv)
{
double o;
int res;

// To illustrate, I chose to set up an infinite loop.
// If the input is correct, we'll "break" it
while(1)
{
printf("Enter a double: ");
res = scanf("%lf",&o);

// Success = 1 read input
if (res == 1)
{
printf("Yahoo, got it right: %fn",o);
break; // We exit the loop
}

// Ah, we failed
printf("Please retry.n");
// popping the CR character to avoid it to be got by the next scanf()
getchar();

// Here we go for another loop.
}

// Good, we got our double.
printf("Hey, sounds like we got outside this infinite loop.n");
}


Example:



user@so:~$ ./a.out 
Enter a double: r
Please retry.
Enter a double: f
Please retry.
Enter a double: 6.543
Yahoo, got it right: 6.543000


Keep in mind this check is not perfect. For example, "frg6sgg" will success and be displayed as 6.0000000 by printf().






share|improve this answer























  • Why does the if case only check if "res" is 1? Sorry I really don't understand this..
    – Ray Ban
    Nov 22 at 23:09










  • When I do it like this: while(1) { printf("Type in your first operand:n"); Input = scanf("%lf", &Operand1); if (Input == 1) break; printf("No valid inputn"); } I get an infinite loop, why?
    – Ray Ban
    Nov 22 at 23:25












  • Understood now :) Got it working. I did not understand the quote of the manual page but your explanation was way better. Thanks a lot sir.
    – Ray Ban
    Nov 22 at 23:58














2












2








2






Manual page of scanf:




On success, these functions return the number of input items successfully matched and assigned; this can be fewer than provided for, or even zero, in the event of an early matching failure.




So here is a sample which could lead you to solve your problem:



#include <stdio.h>

int main (int argc, char* argv)
{
double o;
int res;

// To illustrate, I chose to set up an infinite loop.
// If the input is correct, we'll "break" it
while(1)
{
printf("Enter a double: ");
res = scanf("%lf",&o);

// Success = 1 read input
if (res == 1)
{
printf("Yahoo, got it right: %fn",o);
break; // We exit the loop
}

// Ah, we failed
printf("Please retry.n");
// popping the CR character to avoid it to be got by the next scanf()
getchar();

// Here we go for another loop.
}

// Good, we got our double.
printf("Hey, sounds like we got outside this infinite loop.n");
}


Example:



user@so:~$ ./a.out 
Enter a double: r
Please retry.
Enter a double: f
Please retry.
Enter a double: 6.543
Yahoo, got it right: 6.543000


Keep in mind this check is not perfect. For example, "frg6sgg" will success and be displayed as 6.0000000 by printf().






share|improve this answer














Manual page of scanf:




On success, these functions return the number of input items successfully matched and assigned; this can be fewer than provided for, or even zero, in the event of an early matching failure.




So here is a sample which could lead you to solve your problem:



#include <stdio.h>

int main (int argc, char* argv)
{
double o;
int res;

// To illustrate, I chose to set up an infinite loop.
// If the input is correct, we'll "break" it
while(1)
{
printf("Enter a double: ");
res = scanf("%lf",&o);

// Success = 1 read input
if (res == 1)
{
printf("Yahoo, got it right: %fn",o);
break; // We exit the loop
}

// Ah, we failed
printf("Please retry.n");
// popping the CR character to avoid it to be got by the next scanf()
getchar();

// Here we go for another loop.
}

// Good, we got our double.
printf("Hey, sounds like we got outside this infinite loop.n");
}


Example:



user@so:~$ ./a.out 
Enter a double: r
Please retry.
Enter a double: f
Please retry.
Enter a double: 6.543
Yahoo, got it right: 6.543000


Keep in mind this check is not perfect. For example, "frg6sgg" will success and be displayed as 6.0000000 by printf().







share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 22 at 23:30

























answered Nov 22 at 22:43









Amessihel

1,9631723




1,9631723












  • Why does the if case only check if "res" is 1? Sorry I really don't understand this..
    – Ray Ban
    Nov 22 at 23:09










  • When I do it like this: while(1) { printf("Type in your first operand:n"); Input = scanf("%lf", &Operand1); if (Input == 1) break; printf("No valid inputn"); } I get an infinite loop, why?
    – Ray Ban
    Nov 22 at 23:25












  • Understood now :) Got it working. I did not understand the quote of the manual page but your explanation was way better. Thanks a lot sir.
    – Ray Ban
    Nov 22 at 23:58


















  • Why does the if case only check if "res" is 1? Sorry I really don't understand this..
    – Ray Ban
    Nov 22 at 23:09










  • When I do it like this: while(1) { printf("Type in your first operand:n"); Input = scanf("%lf", &Operand1); if (Input == 1) break; printf("No valid inputn"); } I get an infinite loop, why?
    – Ray Ban
    Nov 22 at 23:25












  • Understood now :) Got it working. I did not understand the quote of the manual page but your explanation was way better. Thanks a lot sir.
    – Ray Ban
    Nov 22 at 23:58
















Why does the if case only check if "res" is 1? Sorry I really don't understand this..
– Ray Ban
Nov 22 at 23:09




Why does the if case only check if "res" is 1? Sorry I really don't understand this..
– Ray Ban
Nov 22 at 23:09












When I do it like this: while(1) { printf("Type in your first operand:n"); Input = scanf("%lf", &Operand1); if (Input == 1) break; printf("No valid inputn"); } I get an infinite loop, why?
– Ray Ban
Nov 22 at 23:25






When I do it like this: while(1) { printf("Type in your first operand:n"); Input = scanf("%lf", &Operand1); if (Input == 1) break; printf("No valid inputn"); } I get an infinite loop, why?
– Ray Ban
Nov 22 at 23:25














Understood now :) Got it working. I did not understand the quote of the manual page but your explanation was way better. Thanks a lot sir.
– Ray Ban
Nov 22 at 23:58




Understood now :) Got it working. I did not understand the quote of the manual page but your explanation was way better. Thanks a lot sir.
– Ray Ban
Nov 22 at 23:58


















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.





Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


Please pay close attention to the following guidance:


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53438567%2fvalidate-input-and-ask-again-if-invalid%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks

Calculate evaluation metrics using cross_val_predict sklearn

Insert data from modal to MySQL (multiple modal on website)