如果我的程序表现得像它应该的那样,真的很困惑。这不是家庭作业,只是我正在编写的一个有趣的三月疯狂预测程序。
char buffer[20];
char team1_name[20]; // 18 chars + new line + null
char team2_name[20];
printf("Who is team 1?\n");
fgets(buffer, sizeof(buffer), stdin);
strncpy(team1_name, buffer, sizeof(team1_name));
team1_name[strlen(team1_name) - 1] = '\0';
printf("\nWho is team 2?\n");
fgets(buffer, sizeof(buffer), stdin);
strncpy(team2_name, buffer, sizeof(team2_name));
team2_name[strlen(team2_name) - 1] = '\0';
printf("\nEnter %s's info:\n", team1_name);
出于好奇,我输入了一个超过 20 个字符的团队名称,它完全跳过了第二个打印语句。我是否在防止缓冲区溢出?是否由用户决定不要放入巨大的东西?我需要flush语句吗?
这是输出:
Who is team 1?
wjefowiejfwoiejfweoifjweoifjweofijweoifj
Who is team 2?
Enter wjefowiejfwoiejfwe's info:
Wins in last 12:
Losses in last 12:
Points per game: