I want to print a prompt message to standard output, and then read a value from standard input entered by the user (for example, a digit).
If the user entered an invalid value, I want to print the prompt again, and read their response again, until they enter a valid value (kind of like how shells work).
The problem is that when the user enters an invalid value, the prompt somehow gets printed twice, which is not what I want.
Here is what I've tried so far, unsuccessfully:
#include <stdio.h>
const char *prompt = "(Enter 1 to continue)> ";
int get_resp1(void)
{
int r;
fputs(prompt, stdout);
r = getchar() - '0';
if (r != 1)
r = get_resp1();
return r;
}
int get_resp2(void)
{
int r;
r = getchar() - '0';
if (r != 1) {
fputs(prompt, stdout);
r = get_resp2();
}
return r;
}
int get_resp3(void)
{
int r;
fputs(prompt, stdout);
do {
r = getchar() - '0';
if (r != 0)
fputs(prompt, stdout);
} while (r != 1);
return r;
}
int main(void)
{
int response;
/* First attempt: */
/* response = get_resp1(); */
/* Second attempt */
/* fputs(prompt, stdout); */
/* response = get_resp2(); */
/* Third attempt: */
/* response = get_resp3(); */
return response != 1;
}
Here's the result I want:
(Enter 1 to continue)> 2
(Enter 1 to continue)>
(Enter 1 to continue)> 1
In the first line, we enter something other than 1, in the second line, we enter a blank line, then finally, we enter 1.
But here is the result I am getting (using all three methods):
(Enter 1 to continue)> 2
(Enter 1 to continue)> (Enter 1 to continue)>
(Enter 1 to continue)> 1
Notice the prompt is printed twice in the second line.
As it is being said, if the input contains the value 1
(with zero or more spaces or tabs) then it will be accepted. Any other combination of character will be discarded.
You can change the code to change the behavior. And this is just an attempt to demo the OP with a similar kind of processing as expected by the OP in the question.
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdbool.h>
#define MAXBUFFSIZE 100
bool getConfirmation(){
printf("\n%s",">> ");
char buff[MAXBUFFSIZE];
unsigned int success = 0;
while( 1 ){
success = 0;
if( fgets(buff,MAXBUFFSIZE,stdin) == NULL){
fprintf(stderr, "%s\n", "Error in input");
break;
}
for( size_t i = 0; i < strlen(buff); i++){
if(isspace(buff[i]))
continue;
else if( isalpha(buff[i]))
break;
else if( isdigit(buff[i]) ){
if( buff[i] == '1'){
success++;
if( success > 1)
break;
}
else{
success = 0;
break;
}
}
}
if( success == 1 )
break;
success = 0;
printf("\n%s",">> ");
}
if( success == 0)
return false;
return true;
}
int main(){
if( getConfirmation() == true )
printf("%s\n","Continued ... ");
else
printf("%s\n","Error in input");
return 0;
}