Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/63.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_Scanf - Fatal编程技术网

C 从文件中读取多个字符串

C 从文件中读取多个字符串,c,scanf,C,Scanf,假设我有一个.txt文件: HEY What's your name My name is xx 在我的C程序中,如何将每一行扫描成不同的字符串 因为如果我 fscanf(myfile, "%s", string) 我只能逐字扫描,不同的行无法识别 有什么好办法吗?您可以使用fgets从文件中连续读取行。但是,您必须事先知道一条线可以具有的最大长度 #define MAX_LEN 100 FILE *fp = fopen("myfile.txt", "r"); char line[MAX_

假设我有一个.txt文件:

HEY
What's your name
My name is xx
在我的C程序中,如何将每一行扫描成不同的字符串

因为如果我

fscanf(myfile, "%s", string)
我只能逐字扫描,不同的行无法识别


有什么好办法吗?

您可以使用
fgets
从文件中连续读取行。但是,您必须事先知道一条线可以具有的最大长度

#define MAX_LEN 100

FILE *fp = fopen("myfile.txt", "r");
char line[MAX_LEN];

while(fgets(line, MAX_LEN, fp) != NULL) {
    // process line
}

fclose(fp);
这里,
fgets(line,MAX_line,fp)
意味着
fgets
将从流
fp
读取最多
MAX_line-1
字节,并将它们存储在
line
指向的缓冲区中。为结尾追加的空字节保留一个字节<如果读取了存储在缓冲区
line
中的换行符,则code>fgets将返回。因此,如果要从
中删除换行符,则应在上述
while
循环中执行以下操作

line[strlen(line) - 1] = '\0';  // overwrite newline character with null byte
e、 g

#包括
int main(){
字符串[128];
FILE*myfile=fopen(“data.txt”、“r”);
而(1==fscanf(myfile,“%127[^\n]”,string)){
printf(“%s\n”,字符串);
}
fclose(myfile);
返回0;
}
#include <stdio.h>

int main(){
    char string[128];
    FILE *myfile = fopen("data.txt", "r");
    while(1==fscanf(myfile, " %127[^\n]", string)){
        printf("%s\n", string);
    }
    fclose(myfile);
    return 0;
}