下面的代码告诉我:
3276560 January
3276560 February
3276560 March
3276560 April
3276560 May
3276560 June
3276560 July
3276560 August
3276560 September
3276560 October
3276560 November
3276560 December
但我期待
1 January
2 February
3 March
4 April
5 May
6 June
7 July
8 August
9 September
10 October
11 November
12 December
我的错误在哪里?
#include <stdio.h>
int main(void){
int i;
char a[10], b[10];
char *ptrMonths[] ={"January","February","Mach","April","May","June", "July","August","September","October","November","December"};
FILE *ptrToMonthFile;
ptrToMonthFile=fopen("Monthsrr.txt", "w");
for (i = 0; i < 12; i++)
{
fprintf(ptrToMonthFile, "%d %s\n", i+1, ptrMonths[i]);
}
fclose(ptrToMonthFile);
ptrToMonthFile=fopen("Monthsrr.txt", "r");
for (i = 0; i < 12; i++)
{
fscanf(ptrToMonthFile,"%d %s\n", a, b);
fprintf(stdout, "%d %s\n", a, b);
}
fclose(ptrToMonthFile);
getch();
}
答案 0 :(得分:2)
几个问题:
a
的类型必须是int
,因为您使用%d
读取它。
int a;
char b[10];
您需要将地址传递给fscanf
:
fscanf(ptrToMonthFile,"%d %s\n", &a, b);
此外:您还应该检查所有文件功能的返回值。任何I / O都可能失败。
答案 1 :(得分:0)
for (i = 0; i < 12; i++)
{
fscanf(ptrToMonthFile,"%s %s\n", a, b);
fprintf(stdout, "%s %s\n", a, b);
}
我已将%d更改为%s&#39; s现在有效。
答案 2 :(得分:0)
fprintf(stdout, "%d %s\n", i+1, ptrMonths[i]);
答案 3 :(得分:0)
应该是int。如果您想将其作为字符串读取,请改用%s。