Use fgets() http://man7.org/linux/man-pages/man3/gets.3.html代替scanf()
获取用户输入的文本。
为此,请替换此行
scanf("%s", c);
使用以下代码:
if (NULL != fgets(c, sizeof(c), stdin))
{
fprintf(pf, "%s", c);
}
else
{
if (0 != ferror(stdin))
{
fprintf(stderr, "An error occured while reading from stdin\n");
}
else
{
fprintf(stderr, "EOF was reached while trying to read from stdin\n");
}
}
为了允许用户读取多行内容,请在上面的代码周围放置一个循环。为此,您需要定义一个条件来告诉程序停止循环:
The following example stops reading in lines when entering a single dot "." and pressing return:
do
{
if (NULL != fgets(c, sizeof(c), stdin))
{
if (0 == strcmp(c, ".\n")) /* Might be necessary to use ".\r\n" if on windows. */
{
break;
}
fprintf(pf, "%s", c);
}
else
{
if (0 != ferror(stdin))
{
fprintf(stderr, "An error occured while reading from stdin\n");
}
else
{
fprintf(stderr, "EOF was reached while trying to read from stdin\n");
}
break;
}
} while (1);