简体   繁体   中英

how to read a text file in c and then split each line into tokens?

The input text file has some numbers per line, numbers are split by space. The first two lines only got one number, and the following lines got three. What I want to do is read each line of the input and store these numbers.

This is what I've got so far:

    int
    main(int argc, char *argv[]) {
        int n = 0;
        char buff[MAX_STRING_LEN]; //MAX_STRING_LEN is defined as 64
        while (fgets(buff,MAX_STRING_LEN, stdin) != NULL) {
            char temp;
            if (n == 0) {
                sscanf(buff, "%s", &temp);
                int h_num = (int)temp;
            } else if (n == 1) {
                sscanf(buff, "%s", &temp);
                int s_num = (int)temp;
            } else {
                sscanf(buff, "%s", &temp);
                char *token;
                token = strtok(&temp, " ");
                int i = 0;
                int a,b,c;
                while (token != NULL) {
                    if (i == 0) {
                        a = (int)token;
                        token = strtok(NULL, " ");
                    } else if (i == 1) {
                        b = (int)token;
                        token = strtok(NULL, " ");
                    } else {
                        c = (int)token;
                        token = strtok(NULL, " ");
                    }
                    i++;
                }
            }
            n++;
        }
        return 0;
    }

The print statement I used to test my code is like:

    printf("%d\n",h_num);
    printf("%d\n%d\n%d\n",a,b,c);

I created a text file like this:

23
34
4 76 91

but the output is not what I expected, it's the address of the pointer I think. (I'm stuck with pointer again =( ) Could someone help me to point out what the problem is? Appreciate it.

In your code, I can see,

int h_num = (int)temp;

and

int s_num = (int)temp;

No, that is not how you convert an aphanumeric string to int .

You need to use strtol() for this purpose.

Then,

sscanf(buff, "%s", &temp);

is wrong. temp is a char , you got to use %c for that.

My suggestion for a better approach:

  1. Read a complete line from file using fgets()
  2. tokenize the input using strtok() , using space ( ) as delimiter , then convert the token (if not NULL) to int using strtol()
  3. continue untill the returned token is NULL

In this case, your code will be much more generic , as don't need to bother seperately about the number of int s present in each line.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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