[RESOLVED] sscanf?

Started by
2 comments, last by GetWindowRect 18 years, 8 months ago
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]
Advertisement
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.
--Sqorgarhttp://gamebastard.blogspot.com
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);
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
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

This topic is closed to new replies.

Advertisement