c - 写入文件时获得不同的输出

标签 c windows file strftime

我编写了一个程序来保存足球队的统计数据。我将统计数据保存在一个文件中,并将所有匹配项记录在另一个名为“record.txt”的文件中。

在我的record.txt文件中,写的格式是:

[opponent name] [current date]

我面临的问题是,有时我在一行中得到“对手姓名”“日期”,有时日期在新行中开始

这是我得到的图像 pic of output file

这是我的代码

time_t rawtime;
struct tm * timeinfo;
char buffer [80];

time (&rawtime);
timeinfo = localtime (&rawtime);
strftime (buffer,80,"%d/%m/%y",timeinfo);

/* current date acquired */
FILE *history;

history = fopen("record.txt", "a");

char opponent[10];   //opponent name

printf("Opponent Name: ");
fgets( opponent, 10, stdin);
fprintf(history, "Opponent: %s %s\n", opponent, buffer);

fclose(history);

最佳答案

fgets(opponent, 10, stdin);

请注意,当您在 stdin 上按回车键时,fgets() 会读取换行符,而您并没有抑制它。如果您希望同一行中的两个字符串抑制换行符,如

size_t n = strlen(opponent);
if (n > 0 && opponent[n -1] == '\n') 
    opponent[n - 1] = '\0';

关于c - 写入文件时获得不同的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28415735/

相关文章:

c - 在 C 中支持和使用 `fortran` 关键字

c - 使用 fork() 运行太多次来遍历目录的递归函数

windows - 通过 IIS 使用 GIT 智能 HTTP

java - APK 文件写入 SD 卡时损坏

c - 从单链表中删除条目

c - 无法读取 C 中的 UNICODE 文本文件

windows - 如何在 Windows 中使用 KDiff3 预处理器命令?

vb.net - 在 VB.NET 中写入文本文件的有效方法

javascript - 如何从绝对网络路径加载javascript文件

c - 文件变量在 C 中的不同函数之间持续存在