#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2013
    Posts
    142
    Rep Power
    2

    Scanning two strings


    this is the file I'm trying to read.
    Code:
    41 Niobium Nb 92.91
    when I use this code
    Code:
        int a;
        char  n[LEN], s[2];
        double w;
    
        i = 0;
    
        fscanf(inp, "%d%s", &a, n);
        printf("%d\n", a);
        printf("%s", n);
    I get the output
    Code:
    41
    Niobium
    But when I change the fscanf line to,
    Code:
    fscanf(inp, "%d%s%s%lf", &a, n, s, &w);
    the output is
    Code:
    41
    what is going on here?
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2013
    Posts
    159
    Rep Power
    19
    First you should always use the width specifier when retrieving strings with the scanf() family of functions to limit the number of characters these functions will try to retrieve to avoid buffer overflows.

    Next how is LEN defined? What is it's value?

    Next you are overflowing your buffer with your variable s. You need at least three characters for the value you have shown, don't forget the end of string character.

    Jim
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2013
    Posts
    142
    Rep Power
    2
    1. the problem was the size of the string s.
    I forgot to consider the null character.
    2. LEN was defined as 20, so there shouldn't have been a problem with that.
    3. Thanks for the advice. I was told the same thing before here, but I keep forgetting the overflow-prevention measure.

IMN logo majestic logo threadwatch logo seochat tools logo