0

in this example i tried to concatenate "same" with "is the best player in his team" using scanf("%[^\n]s",string) to allow scaf to detect the spaces but it didn't work in this code as i have scanf before it and the compiler considers the "enter" after the first entry of the first scanf and it doesn't even go throw this line scanf("%[^\n]s",string) i can't find alternative to make the compiler consider the spaces in this case.

#include <stdio.h>

int main() {
    int i = 4,x;
    double d = 4.0,y;
    char s[] = "sam ",string[50];

    scanf("%d",&x);
    scanf("%lf",&y);
    scanf("%[^\n]s",string);

    printf("%d\n",(i+x));
    printf("%.1lf\n",(d+y));
    printf("%s%s",s,string);
}
  • 2
    After the `scanf("%lf"` line you should read and discard all characters up to the next newline. [See here](https://stackoverflow.com/questions/7898215/how-to-clear-input-buffer-in-c) – M.M Dec 18 '17 at 00:27
  • 3
    Or place a space in the format string to skip over initial whitespace in the input: `" %[^\n]"`. Note that the trailing `s` is not part of the scanset directive. – ad absurdum Dec 18 '17 at 00:29
  • @DavidBowling great it works, Is there any reference to read about this issue to understand it more ? – Mohamed Moustafa Dec 18 '17 at 00:37
  • 1
    [You can read about the `scanf()` family of functions here](http://port70.net/~nsz/c/c11/n1570.html#7.21.6.2). Note that the only directives which _do not_ ignore initial whitespace are `%c`, `%[]`, and `%n`. Of course, newlines are whitespace characters. There are lots of SO questions dealing with the problem of characters left behind in the input stream. [M.M gave a link to a good question with answers about how to clear the input stream](https://stackoverflow.com/a/26081123/6879826) – ad absurdum Dec 18 '17 at 00:45
  • 2
    @MohamedMoustafa -- not sure what you mean exactly by "the `fflush()` also works," but note that `fflush(stdin)` causes undefined behavior according to the Standard. Some systems do define behavior for this, but it is not portable, and should be avoided. – ad absurdum Dec 18 '17 at 00:47
  • 1
    @DavidBowling yes you are right, i just mixed up things, my bad. and thanks a lot for your help, your contribution helped me a lot – Mohamed Moustafa Dec 18 '17 at 00:54
  • You need to check the return value from `scanf()` — it lets you know when things are going wrong. – Jonathan Leffler Dec 18 '17 at 05:35

0 Answers0