Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 写入文件时出现异常字符_C - Fatal编程技术网

C 写入文件时出现异常字符

C 写入文件时出现异常字符,c,C,我创建了一个包含2个char[]和一个int的结构。我创建了一个该结构的数组,并scanf编辑了几个输入,将数据存储到数组中。然后我使用fprintf将这些数据写入文件。但是当我打开文件时,我会在每一条新记录之前看到ā。Idk为什么会这样 以下是相关代码: FILE *outputFile=fopen("1021.txt","ab"); int tickets=0,i=1; struct air s[30]; printf("\nEnter Number of tickets:"); scanf

我创建了一个包含2个char[]和一个int的结构。我创建了一个该结构的数组,并
scanf
编辑了几个输入,将数据存储到数组中。然后我使用
fprintf
将这些数据写入文件。但是当我打开文件时,我会在每一条新记录之前看到
ā
。Idk为什么会这样

以下是相关代码:

FILE *outputFile=fopen("1021.txt","ab");
int tickets=0,i=1;
struct air s[30];
printf("\nEnter Number of tickets:");
scanf("%d",&tickets);
for (i=1;i<=tickets;i++)
{
    printf("\nEnter the name\t");
    scanf("%s",&s[i].name);
    printf("\nEnter the phone number\t");
    scanf("%s",&s[i].phoneNo);
    printf("\n Enter the address\t");

    scanf("%s",&s[i].address);
    printf("Your ticket is confirmed\t");
    getch();
}
for (i=0;i<=tickets;i++)
{
    printf("%s", s[i].name);
    printf("%s", s[i].phoneNo);
    printf("%s", s[i].address);
    fprintf(outputFile,"%s",s[i].name);
    fprintf(outputFile,"%s",s[i].phoneNo);
    fprintf(outputFile,"%s",s[i].address);
}
FILE*outputFile=fopen(“1021.txt”、“ab”);
int=0,i=1;
结构空气s[30];
printf(“\n输入票数:”);
scanf(“%d”和票据);
对于(i=1;i,您的输入循环是

for (i=1;i<=tickets;i++)
代码中还有其他问题,但这解决了直接的“未初始化数据”问题

编辑:其他一些问题

您以“二进制”模式打开了该文件,但您将其用作文本文件。我相信只有在Windows中才需要进行区分

FILE *outputFile=fopen("1021.txt", "at");   // change to "t"
传递给
scanf
的字符串地址不应包含的
&
地址(与
int
不同)。只需传递数组-它将衰减到所需的指针

scanf("%s", s[i].name);                     // removed `&`
由于您没有在文件中写入任何换行符来取消标记字符串数据,因此当您读回数据时,您将不知道每个数据的结束位置和下一个数据的开始位置

fprintf(outputFile, "%s\n", s[i].name);     // added \n
您说一个成员是
int
可能是电话号码,但您是以字符串形式输入的。然而,将电话号码存储为整数是一个坏主意,因为a)它们可能包含一个字符,例如
“+”
或b)可能以前导的
0
开头,当您存储为
int
时,这将丢失。因此,将结构成员
phoneNo
更改为长度足够的
char
数组

scanf
格式说明符
%s
将在它遇到的第一个空格处停止,因此输入语句会更好,它只在找到
换行符或达到长度限制时停止:

int res = scanf("%29[^\n]", s[i].name);
其中定义的数组长度是
[30]
(您没有显示结构)。或者,您可以研究
fgets()
的使用


最后,您应该检查正在调用的函数的返回值,看看它们是否成功
fopen
将告诉您文件是否正确打开
scanf
会告诉你它扫描的条目数,
fgets
会告诉你它是否成功。

需要,什么是
struct air
?你为什么要把二进制文件和文本文件I/O混合在一起?在C数组中,索引是基于
0
的。将
更改为(i=1;如果您没有在文件中写入任何
换行符来取消标记字符串数据,您将有一个很好的老糊涂程序来读取返回的数据。字符串的读取方式与
scanf(“%s”)、&s[i].address不同;
请删除
&
。请注意地址通常包含空格,因此
scanf(“%s”、…)
将在第一个空格处停止。
fprintf(outputFile, "%s\n", s[i].name);     // added \n
int res = scanf("%29[^\n]", s[i].name);