1

I'm trying to write a program where the user has to write two different strings, but after the first string is entered the program ends. This is the code:

int i=0, N=100;   
char car, v1[N+1], v2[N+1];

printf("Insert the first string: \n");
    while ((car=getchar())!=EOF) {
    v1[i]=car;
    i++;
}
i=0;
printf("Insert the second string: \n");
    while ((car=getchar())!=EOF) {
    v2[i]=car;
    i++;
}

In theory after the first string is written and I press CTRL-D (on Mac, it's the same as CTRL-Z) it should print the "Insert the second string" and allow me to write it.

What actually happens is that I have to press CTRL-D again (because it doesn't output the second printf), at that point the program ends, and it outputs (after the first string I wrote) "Insert the second string", but I cannot write it!

Can you help me please?

alk
  • 69,737
  • 10
  • 105
  • 255
Davide
  • 185
  • 1
  • 9
  • Its working fine, Your terminating condition is EOF, you should use F6 or ctrl+z in windows for this. – Lalit Verma Dec 10 '17 at 14:49
  • It appears like the contents of stdout buffer aren't flushed before you use `getchar`. Try adding `fflush(stdout)` after your second printf and before your second loop. – Yashas Dec 10 '17 at 14:52
  • Possible duplicate of [How to avoid press enter with any getchar()](https://stackoverflow.com/questions/1798511/how-to-avoid-press-enter-with-any-getchar) – Déjà vu Dec 10 '17 at 14:52
  • 1
    `getchar()` returns `int` not `char`. – alk Dec 10 '17 at 15:55
  • `getchar()` does not read a string, but only exactly one `char`. Aside to this it needs to be able to somehow indicate failure or end-of-file, that's why it returns an `int` because this way it could return more then the 256 different values it needed to represent any possible value of a `char`. – alk Dec 10 '17 at 17:45
  • @Yashas I tried that but I didn't work... I solved it (not really the way I wanted) by putting my terminating condition as '\n', just to see if the rest of the code worked... – Davide Dec 10 '17 at 17:59
  • @LalitVerma I think it might be a problem on Xcode for Mac then... I've searched a bit more on the topic and it seems that Unix based systems like linux and Mac use ctrl+d, but Xcode on Mac OS work in a different way, that is why it's not working properly... – Davide Dec 10 '17 at 18:05
  • Maybe this could be a problem, or if you really want to know if your program working or not than VM is still an option (Dont know if for MAC) :P – Lalit Verma Dec 10 '17 at 18:06
  • @alk Ok understood! But does it actually effect my program? Just after the getchar I use `v[i]=car;` in order to read my string character by character. What would you suggest to do to read the strings? – Davide Dec 10 '17 at 18:09

0 Answers0