好的!这个东西很新!
这是更大的任务的一部分,我现在遇到的问题是我在文本文件中有一个名称列表(100个名称)。他们是这样写的:
Sam(输入)Oliver(输入)Paul(输入)---依此类推。
因此,每个名称都在自己的行上。我试图将其读入一个char数组,然后将其打印出来以检查其是否有效。之后,我将不得不对它进行其他操作,但我想稍后再解决。现在是我的代码:(文件名等是芬兰语,所以请不要打扰!:D)
#include <stdio.h>
int main() {
FILE *tiedosto;
char *array[100];
char nimi[] = "names.txt";
tiedosto = fopen(nimi, "r");
if (tiedosto == NULL) {
printf("Tiedostoa ei voida avata");
return;
}
int i;
for (i = 0; i < 100; i++) {
fscanf(tiedosto, "%s", &array[i]);
}
fclose(tiedosto);
printf("Tulostetaan taulukko \n");
// printf("%s \n",array);
for (i = 0; i < 100; i++) {
printf("%s \n", array[i]);
}
return 0;
}
您在代码中有几个错误:
在这一行:
fscanf(tiedosto, "%s", &array[i]);
您无需在此处使用与号。这是因为-array
已经是这种类型char*[]
-在这种情况下,您必须避免通过char**
。
在以下代码段中:
if (tiedosto == NULL) {
printf("Tiedostoa ei voida avata");
return; // ***
}
的返回类型main()
是整数,因此它必须传递非空值。任何非零的返回码都将指示程序关闭失败。
在此声明中:
char *array[100];
在array
使用指针阵列旁边太。因此,必须使用malloc()
函数正确初始化它,以免出现段错误。
如果您不想弄乱分配内存等问题,请尝试切换到二维数组声明:
char array[TOTAL_ENTRIES][PER_NAME_LEN];
我已经描述了2-D数组方法以避免代码复杂(请阅读注释以进行解释):
#include <stdio.h>
// Some global macros throughout this program
#define MAX_USERS 100
#define MAX_STRLEN 64
#define EXIT_SUCCESS 0
#define EXIT_FAILURE 1
int main(void) {
const char *file_name = "names.txt";
FILE *fp = fopen(file_name, "r");
char name_list[MAX_USERS][MAX_STRLEN];
int count = 0;
// Using perror() is the best option here
if (fp == NULL) {
perror(file_name);
return EXIT_FAILURE;
}
// Reading the file contents and saving that into 2-D array
while (fscanf(fp, "%s", name_list[count++]) != EOF)
;
// Displaying the saved array contents
for (int i = 0; i < count - 1; i++)
fprintf(stdout, "%s\n", name_list[i]);
return 0;
}
在此程序中,names.txt
文件中的行数可以小于或等于100。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句