0

I used scanf to see the string in terminal . I don't need to use the scanf() to see the printf() values in following code part2?

Part1:

int main ()
 {
     int c;
     printf("hi there");
     scanf ("hey %d",c);// to check the output
     return(0);
 }

part2:

int main ()
{

   const char src[50] = "When in Rome, do as the Romans";
   char dest[50];
   printf("Before memcpy dest = %s\n", dest);
   printf("Before memcpy src1 = %s\n", src);
   memcpy (dest, src, strlen(src)+1);//copying the address
   printf("After memcpy dest = %s\n", dest);
   printf("Before memcpy src2 = %s\n", src); 
}

Why I cannot see the output of hello world without scanf() in terminal; while I can see for multiple printf with memcpy() function?

karthikr
  • 97,368
  • 26
  • 197
  • 188
huuy
  • 15
  • 3
  • waait, what?, your question makes no sense! – Rizier123 Jan 05 '15 at 18:51
  • `printf("hi there\n");` is this your issue? – Gopi Jan 05 '15 at 18:52
  • what "hello word"? And note that the C output functions will buffer output until a newline is encountered in the stream. if you had `printf("Hi there\n");`, you'd get the output immediately. – Marc B Jan 05 '15 at 18:52
  • possible duplicate of [Why does printf not flush after the call unless a newline is in the format string?](http://stackoverflow.com/questions/1716296/why-does-printf-not-flush-after-the-call-unless-a-newline-is-in-the-format-strin) – n. m. could be an AI Jan 05 '15 at 19:09

1 Answers1

1
2 fixes:
  1. Flush the buffer with newline character

    printf("hi there\n");

  2. Using uninitialized variables will lead to undefined beahvior.

    printf("Before memcpy dest = %s\n", dest);

Gopi
  • 19,784
  • 4
  • 24
  • 36
  • 2
    Flushing with `\n` only works if the stream is line-buffered (an interactive device per the implementation, luck, or deliberate choice by the programmer). – Deduplicator Jan 05 '15 at 18:59
  • @Deduplicator Looks like with a clear `printf()` if the output is not been put out then this should be the issue nothing else might cause this issue – Gopi Jan 05 '15 at 19:00
  • 1
    @Gopi What Deduplicator is getting at is that `fflush(stdout)` would be a better solution than `printf("\n")` because it should work regardless of the buffering mode of the output stream. – twalberg Jan 05 '15 at 19:48