C - printf() not working but puts() is working fin

2020-04-21 02:27发布

void read_class_information(head* beginning, int scale_type) {
    puts("hello");
    // printf("hello");
}

I have a simple function called by main and printf() and fprintf() to stdout does not seen to work within it. On the other hand, puts() works fine. I have no files open at the time of the printf() call or any errors. Any suggestions to what the problem might be? Thanks.

标签: c
3条回答
够拽才男人
2楼-- · 2020-04-21 03:05

By default, stream buffering is set to line buffered, which means nothing is really sent to the stream until a new line character \n is found. The three buffering methods are:

  • _IONBF: unbuffered
  • _IOLBF: line buffered
  • _IOFBF: full buffered

You can change the buffering method for any stream. In this case, you may want to change the buffering method for stdout:

setvbuf(stdout, (char *)NULL, _IONBF, 0);

In this way, you don't need to fflush(stdout); everytime you want to print something without a newline. This has some performance issues which may or not affect to you, so you decide which is better for you.

As usual, you have access to the documentation executing man setvbuf (if you have the docs installed, of course).

查看更多
姐就是有狂的资本
3楼-- · 2020-04-21 03:09

Because printf() does not flush the output stream automatically. On the other hand puts() adds a new line '\n' at the end of the passed string. So it's working because the '\n' flushes de stdout.

Try

printf("hello\n");

Or, explicitly flush stdout

fflush(stdout);

right after the printf() statement.

查看更多
迷人小祖宗
4楼-- · 2020-04-21 03:10

Try using the new line character ('\n') at the end of your statement, also make sure you have the appropriate headers.

查看更多
登录 后发表回答