I'm trying to read a constant length string as an array of c for 8 times. Each time i override the content of the previously read array.
The code seems to be working at the first loop cycle, but then as you can see below, I get some weird output. What am I missing?
CODE:
#include <stdio.h>
#define MAX_READ_CYCLES 8
#define MAX_STRING_LENGTH 4
int main(){
int i, cycles;
char a[MAX_STRING_LENGTH+1];
/***************************************************
* BEGIN Read logic
***************************************************/
for(cycles=0; cycles < MAX_READ_CYCLES; cycles++){
i=0;
printf("\nEnter a string: ");
while(i < MAX_STRING_LENGTH){
a[i] = getc(stdin);
i++;
}
a[i] = '\0'; //string end character
fflush(stdin); //cleaning the buffer
printf("String you entered: %s\n", a);
}
/***************************************************
* END
***************************************************/
return 0;
}
OUTPUT:
Enter a string: cccc
String you entered: cccc
Enter a string: cccc
String you entered:
ccc
Enter a string: String you entered:
Enter a string:
abcdand thenefghfor the first two inputs?abcdon the same line correctly. The second one justefgon a new line.fflush(stdin)is not guaranteed to do what you want. It's undefined behaviour on some platforms and unpredictable at best even on those platforms which define it (Linux). On Linux it flushes already read data that has been buffered but not unread data. So your input stream still contains the new line characters which you need to account for. Suggest usingfgetsinstead.