Reputation: 4112
I am trying to read multiple line inputs in c. Very first input that I enter gets print out completely fine, but the rest of them are missing the first character.
So, I am trying to print if the entered name(string) is a valid identifier name or not, and I want to get the inputs in an endless loop. I know there are many similar questions are already posted here, but none of them are working for me. I am not sure what I am doing wrong here. :(
int main() {
char str[1000];
for(;;){
//Below, I have tried every possibility that I can think of
scanf("%[^\n]d%*c%*s", str);
//fgets(str, 1000, stdin);
printf("str[0]: %c\n", str[0]);
//Flushing the Buffer
while ( (dump = getchar()) == '\n' && dump != EOF);
//fflush(stdout);
}
}
I am putting my whole code, just for in case,
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main() {
char str[1000];
int i, dump, check;
for(;;){
check = 0;
scanf("%[^\n]d%*c%*s", str);
//fgets(str, 1000, stdin);
printf("str[0]: %c\n", str[0]);
if ( (str[0] == '_') || ( isalpha(str[0]) ) ){
for (i = 1; i < strlen(str); i++) {
if (isalpha(str[i]) || isdigit(str[i])) {
continue;
} else{
printf("2Invalid\n");
check = 1;
}
}
if (check != 1){
printf("String: %s\n", str);
printf("Valid\n");
}
} else{
printf("Invalid\n");
break;
}
//Flushing the Buffer
while ( (dump = getchar()) == '\n' && dump != EOF);
//fflush(stdout);
}
}
Input: asdasffa Output: str[0]: a String: asdasffa Valid
Input: &asdaf Output: str[0]: a
(when str[0] is "&", not "a")
String: asdaf ValidInput: %asdf Output: str[0]: a
(when str[0] is "%", not "a")
String: asdf Valid
I am guessing the way I am flushing the buffer causing this problem?
Thanks!
Upvotes: 0
Views: 138
Reputation: 212208
The line while ( (dump = getchar()) == '\n' && dump != EOF);
consumes a character. Try adding a call to ungetc
after this so the scanf can see it. And remove the redundant dump != EOF
. If dump == \n
, then it won't be EOF.
Upvotes: 2