简体   繁体   English

从C中的文本文件读取和解析文本

[英]Reading and parsing text from a text file in C

Question: 题:

I am trying to read each line from a file (.txt file below) while storing its contents in the appropriate variables. 我试图从文件(下面的.txt文件)中读取每一行,同时将其内容存储在适当的变量中。 The problem occurs when compiling. 编译时出现问题。 I am told there is a segmentation fault but am not sure why this occurring. 有人告诉我存在细分错误,但不确定为什么会这样。

tester1.txt file(disregard spaces) tester1.txt文件(不考虑空格)

1/12/04 Jones, John $31.11 1/12/04琼斯,约翰31.11美元

12/22/03 Dickinson, Tony $5.04 03/12/22迪金森,托尼$ 5.04

12/15/03 Lee, Jerry $21.12 2003年12月15日,李(Jerry)$ 21.12

12/19/03 Kahn, Chris $83.15 2003年12月19日卡恩,克里斯83.15美元

1/31/04 Bills, Mike $32.00 04/1/31账单,迈克$ 32.00

1/15/04 Lake, Jeff $6.66 1/15/04杰克湖$ 6.66

Code: 码:

int main() {

      int month, day, year;
      float money;
      char *lastname, *firstname;
      static const char filename[] = "tester1.txt";

      FILE *file = fopen (filename, "r");

      if (file != NULL) {  
        char line [128]; /* or other suitable maximum line size */
        while (fgets(line, sizeof line, file ) != NULL) {

          sscanf(line,"%d/%d/%d %s, %s $%f", &month, &day, &year, lastname,
        firstname, &money);
          printf("%d/%d/%d %s, %s $%.2f\n", month, day, year, lastname,
        firstname, money );
          // printf("valid: %s\n", line);  
          //  fputs ( line, stdout ); /* write the line */
        }
        fclose (file);
      }
      else {
        perror (filename); /* why didn't the file open? */
      }
      return 0;

}

You need to allocate memory for the strings, you can't just declare them as pointers: 您需要为字符串分配内存,不能仅仅将它们声明为指针:

char lastname[256], firstname[256];

Also, in the scanf you can specify anything but comma (and space), otherwise the comma is also read as a part of the string: 另外,在scanf您可以指定除逗号(和空格)以外的任何内容,否则逗号也将作为字符串的一部分读取:

sscanf(line,"%d/%d/%d %[^, ], %s $%f", &month, &day, &year, 
                lastname, firstname, &money);

First you have allocate memory for the strings, like perreal said. 首先,您需要为字符串分配内存,就像perreal所说的那样。 Then you have to change the sscanf 然后,您必须更改sscanf

char str_money[100];

sscanf(line,"%d/%d/%d %s%s%s",
       &month, &day, &year, lastname, firstname, str_money);

Because if you scanf %f, you will not get that tidy float number. 因为如果您扫描%f,则不会获得该整洁的浮点数。 And scanf %s only stop at space 而scanf%s只停在太空

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

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