473,409 Members | 2,034 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,409 software developers and data experts.

Programmer wannabee question about sscanf

What advantages does sscanf offer over scanf?

I had the following code:

#include <stdio.h>
#include <string.h>

int main(void)
{
int start, finish, values;
char line[10];

memset(line,0, 10);

printf("Event numbers ? ");
fgets(line, sizeof(line), stdin);
values = sscanf(line,"%d %d", &start, &finish);

printf("start = %d en finish = %d values = %d\n",
start, finish, values);

return 0;
}

but if tha user inputted for example : erte 5 6 ..the output of start
and finished would not be 5 or 6 but some strange value...

I thought that sscanf would find values that are integers and assign
those integer values to the variables?

If not how can I accomplish this?

Mar 4 '06 #1
10 2948
sscanf does no more than scanf does; it just gets its input from a
string rather than from standard input. Both scanf and sscanf are
extremely strict; they expect input that would have been created by the
exact same formatting string using printf.
The most straight-forward way to get the first two numbers from a
string is to loop through the string, character by character, testing
each character to see if it is a digit. Then, when a digit is reached
(and you can, if you want, require and check that the digit either be
the first character in the string or preceded by whitespace) use strtol
to convert the number starting with that digit into the string.
strtol takes a pointer as its second argument, and will put a pointer
to the first character after the number into the variable pointed to by
that second argument. It returns the number.
You then continue to loop through the string until you reach another
digit, after which you can call strtol again!
In general, it is better to write your own code to parse input strings,
rather than use scanf.
I note that you are using memset in your code to zero your buffer
before reading input into it. The code will work equally well without
it, but I don't know the true context this code is used in, so perhaps
it is valid.
Also, you are putting an artificial 10-character limit on the user's
input. If the user wants to define a range between two five digit
numbers, it will not fit, and the end of the second number will be
chopped off. I usually use a function I have written to read the entire
line into dynamically allocated memory, which can be extended as
needed, but increasing the buffer size to 256 would do as well in this
case.
The function I have written to read lines from standard input can be
downloaded at http://www.nic-nac-project.de/~baseb...de/readline.c;
feel free to use it in your code.
I hope all this helps!
Jimmy Hartzell

Mar 4 '06 #2
broeisi wrote:
What advantages does sscanf offer over scanf?
It does not create potential buffer overflow vulnerability when used
with %s.
I had the following code:

#include <stdio.h>
#include <string.h>

int main(void)
{
int start, finish, values;
char line[10];

memset(line,0, 10);
Not really necessary...

printf("Event numbers ? ");
Not terminating printf() with \n may result in no output until an \n is
emitted, or fflush(stdout) is executed.
fgets(line, sizeof(line), stdin);
values = sscanf(line,"%d %d", &start, &finish);

printf("start = %d en finish = %d values = %d\n",
start, finish, values);

return 0;
}

but if tha user inputted for example : erte 5 6 ..the output of start
and finished would not be 5 or 6 but some strange value...

I thought that sscanf would find values that are integers and assign
those integer values to the variables?
No, sscanf() will try to get it's values as specified and will
terminated as soon as it gets them, or as soon as it fails. In your
example above, it fails immediately (for "erte") and `start` and
`finish` remain uninitialised (you'd have been better initialising them
than the string). You should have checked `value` for errors, and you'd
have discovered this.
If not how can I accomplish this?


If you want to get the first two valid integers out of anything user
might decide to input, you'd have to process it yourself. AFAIK,
there's no C function that'll do it for you.

PS
Please ignore post by `j**********@gmail.com` as it has more than it's
fair share of inaccuracies.

--
BR, Vladimir

Avoid the Gates of Hell. Use Linux
(Unknown source)

Mar 4 '06 #3
Re: comp.lang.c
What advantages does sscanf offer over scanf?

I had the following code:

#include <stdio.h>
#include <string.h>

int main(void)
{
int start, finish, values;
char line[10];

memset(line,0, 10);

printf("Event numbers ? ");
fgets(line, sizeof(line), stdin);
values = sscanf(line,"%d %d", &start, &finish);

printf("start = %d en finish = %d values = %d\n",
start, finish, values);

return 0;
}

but if tha user inputted for example : erte 5 6 ..the output of start
and finished would not be 5 or 6 but some strange value...

I thought that sscanf would find values that are integers and assign
those integer values to the variables?

If not how can I accomplish this?


If possible on your system, use getline(), even if extensions are not
usually reccomended. Imposing arbitary limits on a program is not a
good habit to get into.

Here lies the problem:

values = sscanf(line,"%d %d", &start, &finish);

The problem with your slice of code is that you are assigning the
return value of the statement as well as expecting two decimals with a
space between them.:

The should-work way should be:

int start, finish, values;
char line[10];

memset(line,0, 10);

printf("Event numbers ? ");

fgets (line, sizeof(line), stdin);
sscanf (line, "%d","%d", &start, &finish);
sscanf (line, "%d %d", &value);

Hopw that helps and has no compile problems.
Mar 4 '06 #4
"Vladimir S. Oka" <no****@btopenworld.com> writes:
broeisi wrote:
What advantages does sscanf offer over scanf?


It does not create potential buffer overflow vulnerability when used
with %s.

[...]

It does, but the vulnerability is easily controlled for sscanf()
(since you can know the size of the input string), but not easily
controlled for scanf() (since the program generally can't control how
long an input line might be).

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Mar 4 '06 #5
"broeisi" <br*******@gmail.com> writes:
What advantages does sscanf offer over scanf?

[snip]

By using fgets() and sscanf(), you divide the task into two parts:
getting the input line and extracting information from it.

scanf() consumes a variable number of characters from stdin, depending
on the format string and what's actually in the input line. It
commonly leaves a newline character on stdin, to be consumed by the
next input routine you call (which may not be able to handle it
properly). If you're trying to read, say, 3 input fields, and the
input only has 2 valid fields, scanf() will consume those two fields
and may leave you in the middle of the line.

In some cases, scanf() skips whitespace, *including* new-line
characters. If the user doesn't provide all the required fields on a
line, it keeps reading lines until you get all of them (or an error);
that's probably not what you want.

By contrast, fgets() consumes an entire line, including the trailing
newline. (That's not *quite* true; it only reads up to the maximum
number of characters you specify. You can either discard the rest of
the line after fgets(), or you can use a routine like the non-standard
but freely available ggets() that reads the entire line.) Once you
have the line in memory, you can use sscanf() to extract the required
information from it. sscanf(), like scanf(), returns the number of
items successfully translated. If that's less than the number you
asked for, you can reject the entire input line. If your program is
interactive, you can then prompt the user to try again.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Mar 4 '06 #6
Keith Thompson wrote:
"Vladimir S. Oka" <no****@btopenworld.com> writes:
broeisi wrote:
What advantages does sscanf offer over scanf?


It does not create potential buffer overflow vulnerability when used
with %s.

[...]

It does, but the vulnerability is easily controlled for sscanf()
(since you can know the size of the input string), but not easily
controlled for scanf() (since the program generally can't control how
long an input line might be).


Yes, but that's self-inflicted (i.e. bad programming by choice).

--
BR, Vladimir

His heart was yours from the first moment that you met.

Mar 4 '06 #7
Vladimir S. Oka wrote:
broeisi wrote:
What advantages does sscanf offer over scanf?


It does not create potential buffer overflow vulnerability when used
with %s.
I had the following code:

#include <stdio.h>
#include <string.h>

int main(void)
{
int start, finish, values;
char line[10];

memset(line,0, 10);


Not really necessary...

printf("Event numbers ? ");


Not terminating printf() with \n may result in no output until an \n is
emitted, or fflush(stdout) is executed.


How could omitting '\n' possibly result with no output until an '\n' or
fllush is executed? Care to give some kind of example?

Thanks,
Chad

Mar 4 '06 #8
I meant *or fflush()*.

Mar 4 '06 #9
Chad wrote:
Vladimir S. Oka wrote:
broeisi wrote:
>
> printf("Event numbers ? ");


Not terminating printf() with \n may result in no output until an \n
is emitted, or fflush(stdout) is executed.


How could omitting '\n' possibly result with no output until an '\n'
or fllush is executed? Care to give some kind of example?


No need for an example. Have a look at the Standard.

--
BR, Vladimir

My theology, briefly, is that the universe was dictated but not signed.
-- Christopher Morley

Mar 5 '06 #10
Chad wrote:
Vladimir S. Oka wrote:

.... snip ...

Not terminating printf() with \n may result in no output until
an \n is emitted, or fflush(stdout) is executed.


How could omitting '\n' possibly result with no output until an
'\n' or fllush is executed? Care to give some kind of example?


Because a C stream will normally collect output in a buffer until
it has enough to spend the time on a operating system call to
output it. The appearance of a '\n' or a call to fflush() on that
file will force the actual output.

--
"If you want to post a followup via groups.google.com, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
More details at: <http://cfaj.freeshell.org/google/>
Also see <http://www.safalra.com/special/googlegroupsreply/>
Mar 5 '06 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

15
by: AMT2K5 | last post by:
Hello folks, I seem to have recieved a segfault within my function but am unsure on how to resolve it. I understand that it means that somewhere something is trying to access memory that is not...
7
by: Allan Bruce | last post by:
If I have sscanf("FL:%s:%d:%s\n", lGuid, &lID, lFileName); and the last string contains spaces, e.g. my complete string "FL:1234ABCD:3:FileName With Spaces.txt\n" does sscanf just make...
4
by: ishekara | last post by:
Hi, As per the msdn knowledge base.. i find the following "In an application developed with Microsoft C or C/C++, the sscanf() function is a good alternative to the atof() function to convert...
10
by: baumann | last post by:
hi, 1) first test program code #include <stdio.h> int main(void) { char * file = "aaa 23 32 m 2.23 ammasd"; int i2,i3;
4
by: baumann | last post by:
hi all there has 2 program 1) the first test program code #include <stdio.h> int main(void) {
5
by: jchludzinski | last post by:
I'm using strtok() to parse thru a line and read different numbers: float value; char *token; token = strtok( line, " " ); .... sscanf( token, "%f", &value ); These results are less...
22
by: Superfox il Volpone | last post by:
Hello I have some problem with sscanf, I tryed this code but it doesn't works : char* stringa = "18/2005" char mese; char anno; int i_letture; i_letture = sscanf(stringa, "%2s/%4s",...
8
by: bmlclemson08 | last post by:
Hey if anyone could I need to find out how to write a program that will read in any number of integers, including none, and determine which is the largest integer. The part i can't figure out is...
8
by: Artemio | last post by:
Dear folks, I need some help with using the sscanf() function. I need to parse a string which has several parameters given in a "A=... B=... C=..." way, and each has a different type (one is a...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.