Is there a better way for scanf?

Q

QQ

Hello I am running this code
int main(void)
{
char A[3],B[3];
printf("Please input A: \n");
scanf("%2s",A);
printf("Please input B: \n");
scanf("%2s",B);
printf("A is %s,B is %s\n",A,B);
}

I get output if I type A more than 2 chars.

../a.out
Please input A:
asdgc
Please input B:
A is as,B is dg

I know the way to avoid this to use
scanf("%s",A);
However, people ususally don't use in this way
so is it a better way to avoid it?

Thanks a lot!
 
M

Mike Wahler

QQ said:
Hello I am running this code
int main(void)
{
char A[3],B[3];
printf("Please input A: \n");
scanf("%2s",A);
printf("Please input B: \n");
scanf("%2s",B);
printf("A is %s,B is %s\n",A,B);
}

I get output if I type A more than 2 chars.

./a.out
Please input A:
asdgc
Please input B:
A is as,B is dg

I know the way to avoid this to use
scanf("%s",A);
However, people ususally don't use in this way

The reason is that there's no protection from
overflowing the array.
so is it a better way to avoid it?

Limit the input as you're doing above, and simply
throw away any unwanted characters:

#include <stdio.h>

void discard(void)
{
int c = 0;
while((c = getchar()) != EOF && c != '\n')
;
}

int main(void)
{
char A[3] = {0};
char B[3] = {0};

printf("Please input A: \n");
scanf("%2s", A);
discard();

printf("Please input B: \n");
scanf("%2s", B);
discard();

printf("A is %s, B is %s\n",A,B);
return 0;
}

-Mike
 
R

Robert Gamble

QQ said:
Hello I am running this code
int main(void)
{
char A[3],B[3];
printf("Please input A: \n");
scanf("%2s",A);
printf("Please input B: \n");
scanf("%2s",B);
printf("A is %s,B is %s\n",A,B);
}

I get output if I type A more than 2 chars.

./a.out
Please input A:
asdgc
Please input B:
A is as,B is dg

I know the way to avoid this to use
scanf("%s",A);

No, that's not the way to avoid it. In addition to exposing the
program to buffer overflows, this probably won't do what you want. If
the user entered three words, the first one would be read into A, the
second would then be handled by the above statement, but the last word
would still be on the input stream waiting to be picked up by the next
call to scanf.
However, people ususally don't use in this way
so is it a better way to avoid it?

You weren't completely clear on what it is you are trying to avoid. If
you just want to discard the rest of the line after your scanf, try
something like this:

scanf("%*[^\n]%*1[\n]");

You might also consider using fgets and sscanf instead.

Robert Gamble
 
P

Peter Nilsson

Robert said:
... If you just want to discard the rest of the line after your
scanf, try something like this:

scanf("%*[^\n]%*1[\n]");

Note that %[ must match _at least_ one character before scanf will
swallow a subsequent newline. Hence, if the remaining text on the
line is _just_ the newline, this scanf call will leave it there.
Better is something like...

if (scanf("%*[^\n]") != EOF) getchar();
 
R

russfink

Easiest method is use the * modifier which means to scan, but do not
assign, the input. The format string becomes " %2s%*s": the leading
space means skip whitespace (including newlines); %2s means read a
string of 2 characters (ending with null); %*s means read all further
characters on the line, but don't assign. The positional parameter is
NULL in this case (though it can be anything).

#include <stdio.h>

int main(void)
{
char A[3], B[3];
printf("Please input A: \n");
scanf(" %2s%*s", A, NULL);
printf("Please input B: \n");
scanf(" %2s%*s", B, NULL);
printf("A is %s, B is %s\n", A, B);
return 0;
}

Output is -
Please input A:
qwertyuiop
Please input B:
asdfghjkl;
A is qw, B is as

-- Russ
 
R

Robert Gamble

Easiest method is use the * modifier which means to scan, but do not
assign, the input. The format string becomes " %2s%*s": the leading
space means skip whitespace (including newlines);
%2s means read a string of 2 characters (ending with null);

scanf reads characters, not strings, from the standard input stream and
does not expect null character termination.
%*s means read all further characters on the line, but don't assign.

No, it doesn't. The %*s means read and discard a sequence of
"non-white-space characters". If the string in question is "this
doesn't work", the " %2s" will consume the "th" and the subsequent
"%*s" will consume the "is", leaving the rest of the input on the
stream.
The positional parameter is
NULL in this case (though it can be anything).

No, the positional parameter is not NULL, nor can it "be anything".
There must not be a parameter provided at all for an assignment
suppression, doing so will invoke undefined behavior if there is
another conversion later in the same format string that does expect a
corresponding parameter. (It may cause undefined behavior in every
case, I don't feel like looking up the details)

Robert Gamble
 
R

Robert Gamble

Peter said:
Robert said:
... If you just want to discard the rest of the line after your
scanf, try something like this:

scanf("%*[^\n]%*1[\n]");

Note that %[ must match _at least_ one character before scanf will
swallow a subsequent newline. Hence, if the remaining text on the
line is _just_ the newline, this scanf call will leave it there.

I didn't even think about that, good catch, thanks.
Better is something like...

if (scanf("%*[^\n]") != EOF) getchar();

Robert Gamble
 
O

okcozyit

char A[3],B[3];
printf("Please input A: \n");
scanf("%2s",A);
printf("Please input B: \n");
scanf("%2s",B);
printf("A is %s,B is %s\n",A,B);

Solution,buffer stream out
addition code ,fflush(stdin)

char A[3],B[3];
printf("Please input A: \n");
scanf("%2s",A);
fflush(stdin);
printf("Please input B: \n");
scanf("%2s",B);
printf("A is %s,B is %s\n",A,B);
 
R

Richard Bos

okcozyit said:
Solution,buffer stream out
addition code ,fflush(stdin)

That's a perfect solution for the problem of not getting enough
undefined behaviour: you can't fflush() input streams.

Richard
 
L

Lawrence Kirby

Hello I am running this code
int main(void)
{
char A[3],B[3];
printf("Please input A: \n");
scanf("%2s",A);
printf("Please input B: \n");
scanf("%2s",B);
printf("A is %s,B is %s\n",A,B);
}

I get output if I type A more than 2 chars.

./a.out
Please input A:
asdgc
Please input B:
A is as,B is dg

I know the way to avoid this to use
scanf("%s",A);
However, people ususally don't use in this way
so is it a better way to avoid it?

The subject of the thread implies the use of scanf() but scanf() is the
wrong tool for reading line based input. Use fgets() instead. Once you
have read a line you have all of C's string handling functions, including
sscanf(), to interpret it.

Lawrence
 
D

Dave Thompson

True but unnecessary; %s _also_ skips leading whitespace, as does
every conversion except %[...] and %c .
scanf reads characters, not strings, from the standard input stream and
does not expect null character termination.
Right. Although, *scanf %s (and %[..] but not %c) does _add_ a null
character terminator to the value it stores. Note that this is not
counted in the maximum-width specification; the OP correctly had
char A [3] matched to scanf %2s .
No, it doesn't. The %*s means read and discard a sequence of
"non-white-space characters". If the string in question is "this
doesn't work", the " %2s" will consume the "th" and the subsequent
"%*s" will consume the "is", leaving the rest of the input on the
stream.


No, the positional parameter is not NULL, nor can it "be anything".
There must not be a parameter provided at all for an assignment
suppression, doing so will invoke undefined behavior if there is
another conversion later in the same format string that does expect a
corresponding parameter. (It may cause undefined behavior in every
case, I don't feel like looking up the details)
To be precise, a star-suppressed conversion does not 'use up' a
variable argument, so any such argument is matched with the next
unsuppressed conversion if there is one and it is executed; and if
that argument is not valid for that conversion (and NULL in particular
is not valid for any conversion) it's UB. If the bogus argument isn't
used, it is safely ignored; 7.19.6.2p2, at least if we understand
'exhausted' to include terminated due to mismatch or input error as I
think we must given p4 and 7.19.6p1.

- David.Thompson1 at worldnet.att.net
 
J

john_bode

QQ said:
Hello I am running this code
int main(void)
{
char A[3],B[3];
printf("Please input A: \n");
scanf("%2s",A);
printf("Please input B: \n");
scanf("%2s",B);
printf("A is %s,B is %s\n",A,B);
}

I get output if I type A more than 2 chars.

./a.out
Please input A:
asdgc
Please input B:
A is as,B is dg

I know the way to avoid this to use
scanf("%s",A);
However, people ususally don't use in this way
so is it a better way to avoid it?

Thanks a lot!

The approach I've adopted over the years, especially with interactive
input, is to read the whole line into memory as a single
dynamically-sized buffer, and then tokenize and parse that buffer.
This has the advantage of consuming all the characters in the input
stream so that you don't have garbage lying around, and it allows you
to verify your input before assigning it. Here's an example:

/*
** Retrieve the next input line from the specified stream,
** stripping off the trailing newline
*/
char *getNextLine(FILE *stream)
{
/*
** Internal line buffer. Dynamically allocated so
** it can deal with lines of arbitrary length. Declared
** static so that only this function has to deal with
** memory management. Pros: memory management is
** encapsulated in this one function, so no memory
*/ leakage. Cons: not re-entrant or thread safe.

static char *buffer = NULL;
static size_t bufsiz = 0;

/*
** Temporary input buffer; reads 512 bytes at a time
** which are then appended to the permanent buffer
*/

char inbuf[512] = {0};
char *tmp = NULL;

/*
** Clear the buffer for each new line.
*/
if (buffer)
{
free(buffer);
buffer = NULL;
bufsiz = 0;
}

/*
** Keep reading input until we hit a newline or EOF, or
** an error occurs (for this example, no distinction is
** made between EOF or error; we just return the buffer or
** NULL in either case.
*/
while (fgets(inbuf, sizeof inbuf, stream))
{
/*
** Extend the buffer as necessary.
*/
tmp = realloc(buffer, strlen(inbuf) + bufsiz + 1);
if (tmp)
{
buffer = tmp;
buffer[bufsiz] = 0;
bufsiz += (strlen(inbuf) + 1);
}
else
{
fprintf(stderr, "Could not extend input buffer past %lu
bytes!\n", (unsigned long) bufsiz);
free(buffer);
buffer = NULL;
bufsiz = 0;
return NULL;
}

/*
** Append the input buffer to the permanent buffer.
*/
strcat(buffer, inbuf);

/*
** Search for the newline. If it's present, replace
** it with the 0 terminator and exit the loop.
*/
if (strchr(buffer, '\n'))
{
*strchr(buffer, '\n') = 0;
break;
}
}

return buffer;
}

int main(void)
{
char A[3],B[3],*line;

for(;;)
{
printf("Please input A: \n");
line = getNextLine(stdin);
if (strlen(line) > 2)
{
printf("Input too long -- try again\n");
}
else
{
strcpy(A, line);
break;
}
}
/*
** Repeat for B
*/
printf("A is %s,B is %s\n",A,B);
}

Yeah, it's ugly. It can be prettied up a bit (unfortunately I can't
spend a ton of time on it right now). But this is the reality of
interactive input in C -- you have to build your own blade guards.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top