I'm writing a program which is supposed to read two strings that can contain line breaks and various other characters. Therefore, I'm using EOF (Ctrl-Z or Ctrl-D) to end the string.
This works fine with the first variable, but with the second variable, however, this seems to be problematic as apparently something is stuck in the input buffer and the user doesn't get to type in anything.
I tried to clean the buffer with while (getchar() != '\n');
and several similar variations but nothing seems to help. All cleaning attempts have resulted in an infinite loop, and without cleaning, adding the second variable is impossible.
The characters for both of the variables are read in a loop like this: while((c = getchar()) != EOF)
, which would suggest it is EOF what I have stuck in my buffer. Or does it affect the behavior of the program in some other way? Is there something wrong with the logic I'm using?
I'm starting to get bit desperate after struggling with this for hours.
[edit: added code below]
[edit 2: clearerr() seems to make this EOF solution work after all.
It seems to run in its original form like I intended under Linux, I was trying it with Windows yesterday.]
code:
#include <stdio.h>
#include <string.h>
int main(void)
{
int x = 0;
int c;
char a[100];
char b[100];
printf("Enter a: ");
while((c = getchar()) != EOF)
{
a[x] = c;
x++;
}
a[x] = '\0';
x = 0;
/*while (getchar() != '\n'); - the non-working loop*/
printf("\nEnter b: ");
while((c = getchar()) != EOF)
{
b[x] = c;
x++;
}
b[x] = '\0';
printf("\n\nResults:\na: %s\n", a);
printf("b: %s\n", b);
return(0);
}
[edit 3:]
Dynamic memory issue:
My program is also supposed to handle strings longer than 100 characters. Originally I intended to solve that by dynamic memory allocation, but when I had problems with the infinite loop described above and memory-related crashes I left it out and switched over to char[100].
I think what I tried was generally something like this:
while((c = getchar()) != EOF)
{
a = malloc(sizeof(char));
a[x] = c;
x++;
}
Is that a possible (or sensible) way to do that? I'm trying to allocate more memory for every character that's being handled there. Individually. With code like that (this example contains probably syntax errors) I experienced crashes, so looks to me malloc might not be the right function here, or I'm trying it wrong. Supposing it's even possible.