Home > OS >  getchar() got frozen while assigning the return value to a char array
getchar() got frozen while assigning the return value to a char array

Time:09-19

I am doing my C assignment for colleage. The task is requiring the function uses getchar() to read input from user and save it to a char[] type variable. Here is my code:

void readLine(char str[], int length){
    
    int i = 0;
    if(length < 1) return;
    
    while(1){
        str[i] = getchar(); 

        if(str[i] == '\n'){
            str[i] == '\0';
            return;
        }
        if(i < length - 1) i  ;
        
    }
}

printf("String? ");
char inputString[LENGTH];
readLine(inputString, LENGTH);

the terminal will get frozen while the value of getchar() is assigned to str[i]. If I assigned it to an int type variable, no complains comes from terminal. According to the doc of getchar(), it is returning int type and it is possible to assign to a char[]. So I am confused what I did wrong.

CodePudding user response:

your problem is so simple:

  1. instead of the line str[i] == '\0'; it's str[i] = '\0'; , not the difference between = and == , the first one is used in assignment , the second one is used to test whether the variable equals to this value or not.
  2. you have a warning in this line str[i] = getchar(); as getchar() returns int not char and my compiler gave me this warning :

Clang-Tidy: Narrowing conversion from 'int' to signed type 'char' is implementation-defined

so you should cast the returned value from getchar() by writing str[i] = (char)getchar();

  1. also , you should modify the condition if(str[i] == '\n') into if(str[i] == '\n' || i == length - 1) , imagine that the user entered number of chars exceeded the LENGTH , then you should store only the first chars that could fit.

with these only 3 small modifications , this is the edited code :

    #include<stdio.h>
    #include <stdlib.h>

    #define LENGTH  10

    void readLine(char str[], int length)
    {

        int i = 0;
        if(length < 1) return;

        while(1)
        {
            str[i] = (char)getchar();

            if(str[i] == '\n' || i == length - 1)
            {
                str[i] = '\0';
                return;
            }
            if(i < length - 1) i  ;

        }
    }

    int main(){

        printf("String? ");
        char inputString[LENGTH];
        readLine(inputString, LENGTH);
        printf("%s", inputString);
    }

and this is the output :

String?test
 test
  • Related