简体   繁体   中英

Strtol doesn't return the correct endptr - C

I have to parse data from file rows and for that I'm now using strtol() function.

I have for example this row in the text file: 1 abc

This is for example, an invalid row as this specific row has to contain one and only one integer value.

Now when I'm using strtol this way:

    FILE *fs;
    fs = fopen("file.txt", "r");
    char* ptr = NULL; // In case we have string except for the amount
    char lineInput[1024]; // The max line size is 1024
    fscanf(fs, "%s", lineInput);
    long numberOfVer = strtol(lineInput, &ptr, BASE);
    printf("%lu\n%s\n", numberOfVer, ptr); // Here I test the values, I expect to get 1 followed by newline and abc
    if (numberOfVer == 0 || *ptr != '\0') { // Not a positive number or there exists something after the amount!
        fprintf(stderr, INVALID_IN);
        return EXIT_FAILURE;
    }

But, the ptr string is not "abc" or " abc", it's an empty string... Why is that? According to the documentation it has to be " abc".

scanf("%s") skips whitespace. So if you have the input "1 abc" and scan it in with

fscanf(fs, "%s", lineInput);

lineInput contents end up being "1" and the rest of the string stays in the input buffer ready for the next input operation.

The usual function for reading lines is fgets()

    FILE *fs;
    fs = fopen("file.txt", "r");
    char* ptr = NULL; // In case we have string except for the amount
    char lineInput[1024]; // The max line size is 1024
    // using fgets rather than fscanf
    fgets(lineInput, sizeof lineInput, fs);
    long numberOfVer = strtol(lineInput, &ptr, BASE);
    printf("%ld\n%s\n", numberOfVer, ptr); // Here I test the values, I expect to get 1 followed by newline and abc
    //      ^^^ numberOfVer is signed
    if (numberOfVer == 0 || *ptr != '\0') { // Not a positive number or there exists something after the amount!
        fprintf(stderr, INVALID_IN);
        return EXIT_FAILURE;
    }

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