Search code examples
c++cstringinputgetchar

Struggling with getchar() function in C


I am trying to replace multiple blanks with a single blank.

#include <stdio.h>
#include <stdlib.h>
#define MAXLINE 500

main() {
    char text[MAXLINE];
    int i;

    for(i = 0; (text[i] = getchar()) != EOF && text[i] != 'x'; i++) {
        if(text[i] == ' ')
            i++;

        while((text[i] = getchar()) != EOF && text[i] != 'x' && text[i] == ' ');

        if(text[i] == EOF || text[i] == 'x')
            break;
    }

    text[i] = '\0';

    printf("\n\n-- Result --\n%s", text);
}

I know that getchar() expects a character after enter was pressed, but I have seen many times, how people use it to get a whole string till EOF is found. Even in this example, it works if I comment out the while loop (I get a correct string if I write a single word without blanks). What I want is to put every single char that a person writes in an array. Is getchar() function okay to use in this case? If yes, what do I need to change in this code to make it work, because now it prints only some characters (if the while loop is not commented out)? As I said, it works if I write a word apple or similar without any blanks and without the while loop.


Solution

  • To read all the input from user until end of input, skiping spaces which occurs several times in line, use something like this.

    #include <stdio.h>
    #include <stdlib.h>
    #define MAXLINE 500
    
    int main() {
        char text[MAXLINE];
        int i;
        int c;
    
        c = getchar();
        for (i = 0; c != EOF && i < MAXLINE-1; ++i) {
            text[i] = c;
    
            if ( c != ' ' ) {
                c = getchar();
            } else {
                while ( c == ' ' )
                    c = getchar();
            }
        }
        text[i] = '\0';
    
        printf("\n\n-- Result --\n%s", text);
    }