I have the following task at the university 1. terms:
- Read one char from stdin
- Concatenate it with the older chars you read
- Use realloc to get space for one more char
- Do this till you read '\0'
So this is my code:
#include <stdio.h>
#include <stdlib.h>
char * readString(void){
int nChar = 1;
int cntr = 0;
char * str = NULL;
char z;
while((z = getchar()) != '\0'){
str = realloc(str, nChar * sizeof(char));
*(str+cntr) = z;
cntr++;
nChar++;
}
return str;
}
int main(int argc, char *argv[]) {
readString();
}
The Problem is that I never read the '\0' char. When I asked my professor he said only that I am also allowed to use getch, fgets and scanf to read one char from the stdin.
Can someone help? I don't have any clue.
I edited my code now. Is this right?
char * readString(void){
int nChar = 1;
int cntr = 0;
char * str = NULL;
char z;
while(1){
if((z = getchar()) != '\n'){
str = realloc(str, nChar * sizeof(char));
*(str+cntr) = z;
cntr++;
nChar++;
} else {
str = realloc(str, nChar * sizeof(char));
*(str+cntr) = '\0';
break;
}
}
return str;
}