在C语言中将文件中的行添加到数组中
我试图读取一个文件,每行都有一个名称,如 吉姆 艾比 提摩太 并将每个名称存储在数组中的一个点中,以便以后使用每个单独的名称。这是我的代码,但我认为名称存储不正确,因为如果我更改文件中名称的顺序,名称上的操作也会更改。操作取决于名称,而不是位置在C语言中将文件中的行添加到数组中,c,string,file,lines,C,String,File,Lines,我试图读取一个文件,每行都有一个名称,如 吉姆 艾比 提摩太 并将每个名称存储在数组中的一个点中,以便以后使用每个单独的名称。这是我的代码,但我认为名称存储不正确,因为如果我更改文件中名称的顺序,名称上的操作也会更改。操作取决于名称,而不是位置 FILE *ptr_file; // pointer to file char name[100]; size_t k=0; ssize_t read; char *line = NULL; while ((read= getline(&lin
FILE *ptr_file; // pointer to file
char name[100];
size_t k=0;
ssize_t read;
char *line = NULL;
while ((read= getline(&line, &k, ptr_file))!=-1)
{
fscanf(ptr_file, "%s", &name);
printf("%s ",name);
}
`我正试着用这些名字做类似的事情
for (i =0; i <length-1; i++)
//for the length of the string add each letter's value up
{
num = num + name [i];
}
但是当我切换名称在列表中的位置时,num的值也会发生变化。可能是这样的。在这段代码中,我假设文件中的名称少于200个。您可以通过更改名称数组的大小来更改此设置
FILE *ptr_file; // pointer to file
char names[200][100];
size_t k=100;
size_t namesCount = 0;
size_t read;
while ((read= getline(names[namesCount], &k, ptr_file))!=-1) //reading name to names array
{
printf("%s ",names[namesCount++]);//printf just readed name
}
当您传递空指针时,getline会为您分配内存。 我已经对代码进行了注释以进行解释
#include <stdio.h>
#include <stdlib.h>
#define THRESHOLD (5)
int main(int argc,char** argv) {
// the file containing the names (one in each line)
char* fn = "test";
// lets open the file (you should check the result!)
FILE* file = fopen(fn,"r");
// allocate memory for the array
char** names = (char**)malloc(THRESHOLD * sizeof(char*));
size_t i;
// set all the values to NULL
for(i=0; i<THRESHOLD; i++) {
names[i] = NULL;
}
// initialize the count
size_t count = 0;
// read all names until EOF and resize the array if needed
while(getline(&names[count],&i,file) != EOF) {
count++;
if(count >= THRESHOLD) {
names = (char**)realloc(names,(count+THRESHOLD)*sizeof(char*));
}
}
// resize (shrink) the array to the actual size
names = (char**)realloc(names,count * sizeof(char*));
// do something with the names (i just print them)
for(i=0; i<count; i++) {
printf("element %d, value %s",i,names[i]);
}
// you have to free the memory (allocated by getline)
for(i=0; i<count; i++) {
free(names[i]);
}
// you have to free memory (allocated by you)
free(names);
return 0;
}
很难理解您的意思,但似乎有两个基本的逻辑问题,您忽略了其他答案中强调的特定技术点 1代码使用getline读取一行,并在第行中丢弃结果,然后立即使用fscanf从文件中读取更多文本 2 fscanf从文件中读取的每个名称都会覆盖名称缓冲区,该缓冲区是一个最多99个字符的字符串加上一个空终止符 当您来处理缓冲区时,它将只包含通过调用fscanf读取的姓氏,或者如果文件中有零行或一行,则不包含任何内容。另外,fscanf格式参数%s告诉fscanf读取一个字符串,直到第一个空格,包括制表符或换行符,这对于简单的名称可能很好,但如果您想要第一个和第二个名称,则不需要 这意味着更改文件的顺序可能会更改读取文件的例程结束时名称缓冲区中的名称。这就是num的值不同的原因。请检查getline的manpage,不要在堆栈中分配缓冲区的情况下使用它。此外,它不能是数组文字,它应该是指针*名称将被修改。