写入文件时获取不同的输出

时间:2015-02-09 17:32:35

标签: c windows file strftime

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

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

  

[对手名] [当前日期]

我面临的问题是,有时候我会在一行中得到“对手名字”“日期”,有时日期会以新的一行开头

这是我得到的图像 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);

1 个答案:

答案 0 :(得分:3)

fgets(opponent, 10, stdin);

请注意fgets()stdin上按Enter键时会读取换行符,并且您没有禁止它。如果你想要同一行中的两个字符串都抑制换行符,如

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