[RESOLVED] sscanf?

This topic is 5179 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

I am trying to save options in my program to a file in the format of description {tab} integer {newline}. the description and integer value are seperated by a \t tabstop char and a \n newline char at the end. When I retrieve the options from the textfile with fstreams getline() function, I retrieve the text as it was saved with no problem. However, when I use sscanf to try to put the data into corresponding variables to utilize them, I get Access Violations. The code I am using is. option is the value of getline(), szOpt is the variable to hold the option description, and iOpt is the variable to hold its value.
sscanf(option, "%10s\t%d", szOpt, iOpt);


I figured I was using it wrong, so I tried using strcspn to get the position of the description and the integer value. I tried to atoi() the integer value into a variable and I get an Access violation with that as well. I looked on some sites for atoi examples and they use strings like " -9542 text text text "; and it supposably strips the integers, so I tried passing the full string. When I do that, it does not error out, but it also does not set the correct value into the variable. Is there something I am doing wrong? Any help or thoughts would be appreciated. Thank you in advance [Edited by - GetWindowRect on August 17, 2005 12:21:25 AM]

Share on other sites
Unlike printf, scanf reads into variables via pointers. This means you have to pass the reference as variables, unless the variable is already a pointer. Try using an & for your integer:

sscanf(option, "%10s\t%d", szOpt, &iOpt);

General rule of thumb: strings don't use &, pretty much everything else does.

Share on other sites
iOpt should be a pointer to an int. If you just pass an int, the function silently transforms it into a pointer (variadic functions do not have any type checking of the variable parameters!) and uses its value as the address of the variable it should write to. Which is very likely to cause an access violation. [smile]

sscanf(option, "%10s\t%d", szOpt, &iOpt);

Share on other sites
I didn't know that, my char always worked fine, but my integer didn't, that would explain it. I searched and searched for examples or explanations, and nothing I could find mentioned that. Thank you very much for your help, it works perfectly now (for the most part), back to trying to figure out my other code. Thank you again

• Game Developer Survey

We are looking for qualified game developers to participate in a 10-minute online survey. Qualified participants will be offered a \$15 incentive for your time and insights. Click here to start!

• 11
• 15
• 21
• 26
• 11