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:
- instead of the line
str[i] == '\0';
it'sstr[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. - you have a warning in this line
str[i] = getchar();
asgetchar()
returnsint
notchar
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();
- also , you should modify the condition
if(str[i] == '\n')
intoif(str[i] == '\n' || i == length - 1)
, imagine that the user entered number of chars exceeded theLENGTH
, 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