开发者

long integer in C

How can I read a long integer with 12 or 13 digits (like a ISBN number of a book) in C? I want to read the number from a text file with information of books(ISBN/name/writer).

The content of the text file is like this:

0393312836

A Clockwork Orange

Anthony Burgess

0199536759

Middlemarch

Bret Easton Ellis

...

...

...

and I am using this code:

int main(void){

    FILE *f;
    char name[MAX], writer[MAX], line[MAX];
    long isbn;

    f=fopen("path.txt","r");
    if(f == NULL){
        return 0;
        }

    while (fgets(line, 1024, f) != NULL){

        sscanf(line,"%ld", &isbn);
        printf("ISBN: %ld\n",isbn);

        fgets(nome, 1024, f);
        printf("NAME: %s",name);

        fgets(line, 1024, f);
        printf("WRITER: %s",writer);


        }
   开发者_高级运维 fclose(f);

    return 0;

}

he is able to read the names of the books and the writers, but he only reads the numbers if they have 9 digits or less. what do I have to do to make this work?


I think for an ISBN you would be much better using a string. You won't need to perform arithmetic on the value, you can store leading zeroes and you'll want a string to store the X that you can get in an ISBN 10 checksum.


Just read it as string (char array) and treat it so. With an int you also lose the important zeros at the start along with the limited range. ISBN numbers, phone numbers and the like are better treated as strings, because they don't represent real numbers (in a mathematical sense), but are just identifiers.


Try using an unsigned long long and the %llu specifier. The former should be a 64-bit number on most platforms.

You could as well try reading it as a string. It depends on whether you want to manipulate it as a string or as a number later.

For example, if you want to sort them alphabetically, read them as strings. If you want to sort them as numbers, treat them as numbers.


It might be best to read them in as Strings or char arrays. ISBN numbers are numbers in the sense that you'll be doing calculations on them. Instead, they are more like a reference string that just so happens to be numeric. Reading in a character array will let you get ISBN numbers that contain dashes or other separators as stated here: http://www.isbn.org/standards/home/isbn/international/html/usm4.htm

If you truly want to store them as numbers, you should read it in as a char array and clean it up in case there are spaces, dashes or other non-numeric characters in the input.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜