Francis
Francis

Reputation: 1151

Why is sscanf skipping the first 4 characters in each string?

I am trying to phrase a file. Each line has a tag and a value. I want to look for a specific tag and then return the associated value.

I am using sscanf to read the tag and value into two variables that I analyses. However sscanf is skipping the first for characters in the string I send it.

sscanf(line.c_str(), "%s%d", &tag, &value);

For example, if the string is "NumPoints 5" then tag gets "oints". It is consistently skipping the first four characters. I have checked, getline is getting the full line, something is going wrong at the sscanf part.

What am I doing wrong?

Here is my code:

int readNumberOfWaypointsInFile(char* filename)
{
    int num_waypoints = 0;

    std::fstream file;
    file.open(filename, std::ios::in);

    std::string line;

    std::string tag;
    int value;

    if (file.is_open())
    {
        while (getline (file, line))
        {
            sscanf(line.c_str(), "%s%d", &tag, &value);

            if(tag == "NumPoints")
            {
                num_waypoints = value;
                break;
            }
        }
    }

    file.close();

    return num_waypoints;
}

Upvotes: 0

Views: 204

Answers (1)

John Zwinck
John Zwinck

Reputation: 249394

Enable warnings in your compiler, and pay attention to them (e.g. g++ -Wall -Wextra -Werror). This would have told you your problem: you are passing the address of a C++ string to the C function sscanf() which expects a C-style string (char array). This is undefined behavior.

Upvotes: 4

Related Questions