简体   繁体   English

使用 fscanf 从用空格分隔的文件中读取多个字符串

[英]Reading multiple strings from file seperated with space, using fscanf

So i want to read some strings from a text file that are seperated with spaces.所以我想从一个用空格分隔的文本文件中读取一些字符串。 The code i have been using is this:我一直在使用的代码是这样的:

int main() {
  char name[9];
  char surname[20];
  char phone[10];
  int code, nscan;
  char termch;
  FILE* infile;

 infile = fopen("I4F6.txt", "r");
if (infile == NULL)
 printf("Error reading text file\n");


 while (TRUE){

nscan= fscanf(infile, "%[^ ] %[^ ] %[^ ] %d%c",
                         name, surname, phone, &code, &termch);


 printf("%s %s %s %d\n", name ,surname, phone, code);


  if (nscan == EOF)
    break;
  if (nscan != 5 || termch != '\n')
    printf("Error line\n");
  }   
   return 0;
}     

An the text file goes like this, with the name first, then the surname, a phone number that needs to be saved as string and a code.一个文本文件是这样的,先是名字,然后是姓氏,需要保存为字符串的电话号码和代码。

nikos dimitriou 6911111112 1
maya satratzemi 6933333332 20
marios nikolaou 6910001112 15
maria giannou 6914441112 1
dimitra totsika 6911555111 14
giannis pappas 6911111222 16
nikos ploskas 6911111662 20

But the result i get from this printf is this:但是我从这个 printf 得到的结果是这样的:

nikos  6911111112 1

maya  6933333332 20

marios  6910001112 15

maria  6914441112 1

dimitra  6911555111 14

giannis  6911111222 16

nikos  6911111662 20

Error line
nikos  6911111662 20   

So as you can see it skips all the surnames and produces an error line.如您所见,它会跳过所有姓氏并生成错误行。

So what should I do to read and store every value seperated with space from the text file into a variable?那么我应该怎么做才能将文本文件中以空格分隔的每个值读取并存储到变量中?

Thanks for your time谢谢你的时间

OP's key problem is using char phone[10]; OP的关键问题是使用char phone[10]; to store "6911111112" which needs 11 char .存储需要 11 个char "6911111112" This all leads to undefined behavior with the unlimited %[^ ]这一切都会导致无限%[^ ]未定义行为

what should I do to read and store every value separated with space from the text file into a variable?我应该怎么做才能将文本文件中用空格分隔的每个值读取并存储到变量中?

*scanf() is difficult to use to detects lines and not get fooled with line endings like "\\r\\n" . *scanf()很难用于检测并且不会被像"\\r\\n"这样的行结尾所迷惑。 Better to read the line and then parse it and use width limited fields.最好阅读该,然后解析它并使用宽度受限的字段。

Consider using %n (it stores the scan offset) to detect a proper scan.考虑使用%n (它存储扫描偏移量)来检测正确的扫描。

char name[9];
char surname[20];
char phone[10+1];

char buf[100];
while (fgets(buf, sizeof buf, infile)) {
  int n = 0;
  sscanf(buf, " %8[^ ] %19[^ ] %10[^ ]%d %n", name, surname, phone, &code, &n);

  // incomplete scan or extra text detected
  if (n == 0 || buf[n]) {
    printf("Error line\n");  // do not use name, surname, phone, code
    break;
  }

  printf("%s %s %s %d\n", name, surname, phone, code);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM