Reputation: 115
I'm having a problem with reading char in C. I need to ask for user input until the user gives me 'x' or 'X' to stop.
char input[size] = {};
printf("Type 'x' or 'X' to stop input mode.\n");
while(strcmp(input,"x")!=0||strcmp(input,"X")!=0){
printf(":");
scanf("\n%c", &input);
}
But still it does not work well.
Upvotes: 0
Views: 3046
Reputation: 40145
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#ifdef CHAR_BASE
int main(){
char input = 0;
printf("Type 'x' or 'X' to stop input mode.\n");
while(tolower(input) != 'x'){
printf(":");
scanf(" %c", &input);
}
return 0;
}
#else //STRING_BASE
int main(){
char input[16] = {0};
printf("Type 'x' or 'X' to stop input mode.\n");
while(strcmp(input,"x") && strcmp(input,"X")){
printf(":");
scanf("%s", input);
}
return 0;
}
#endif
Upvotes: 0
Reputation: 2204
Edit- based on the comments.
char input = getchar();
while( input != 'x' && input != 'X' ) {
// your code
input = getchar();
}
Upvotes: 1
Reputation: 1450
The input
variable when used without square brackets is already a pointer, you don't need to use &
.
Also input
must be initialized before entering the while loop.
Upvotes: 1