Rowel
Rowel

Reputation: 115

C: char user input in command prompt

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

Answers (3)

BLUEPIXY
BLUEPIXY

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

Dinesh
Dinesh

Reputation: 2204

Edit- based on the comments.

char input = getchar();
while( input != 'x' && input != 'X' ) {
    // your code
    input = getchar();
}

Upvotes: 1

Fernando
Fernando

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

Related Questions