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! 11 2882
"QQ" <ju****@yahoo.com> wrote in message
news:11*********************@g44g2000cwa.googlegro ups.com... 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
QQ wrote: 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
Robert Gamble wrote: ... 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();
You might also consider using fgets and sscanf instead.
--
Peter
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 ru******@yahoo.com wrote: 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
Peter Nilsson wrote: Robert Gamble wrote: ... 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
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);
"okcozyit" <ok******@gmail.com> wrote: 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
On Wed, 08 Jun 2005 14:23:28 -0700, QQ wrote: 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
On 8 Jun 2005 19:32:02 -0700, "Robert Gamble" <rg*******@gmail.com>
wrote: ru******@yahoo.com wrote: 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);
True but unnecessary; %s _also_ skips leading whitespace, as does
every conversion except %[...] and %c .
%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.
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 . %*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)
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
QQ wrote: 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. This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
by: darklight |
last post by:
Q: write a program so that it excepts six even numbers
or until the number 99 is entered
please explain why one is better than the other,
if that is the case.
A1:
/*EX6-1.C TO COUNT AND...
|
by: darklight |
last post by:
Q: write a program so that excepts six even numbers
or until the number 99 is entered.
I should of add display only the even numbers entered
sorry!!
the two programs that were wrote done this:
...
|
by: Peter Mount |
last post by:
Hello
I'm having trouble with " scanf("%c", &answer);" on line 20 below. When I
run the program in cygwin on Windows 98SE it skips that line completely and
ends the program. Does scanf have...
|
by: hugo27 |
last post by:
obrhy8 June 18, 2004
Most compilers define EOF as -1. I'm just putting my toes
in the water with a student's model named Miracle C. The
..h documentation of this compiler does state that when...
|
by: sushant |
last post by:
hi
why do we use '&' operator in scanf like scanf("%d", &x); but why not
in printf() like printf("%d" , x);
thnx in advance
sushant
|
by: kathy |
last post by:
I try to read a text file with format:
11 1.11111
22 2.22222
33 3.33333
....
I try to use fscanf() to read the data back. What is the better way?
|
by: main() |
last post by:
I know this is the problem that most newbies get into.
#include<stdio.h>
int main(void)
{
char a;
scanf("%c",&a); /*1st scanf */
printf("%c\n",a);
scanf("%c",&a); /*2nd scanf*/...
|
by: weidongtom |
last post by:
Hi,
I was working on the following problem and I managed to get a
solution, but it's too slow. And I am still in search for a better
algorithm. Please enlighten me.
...
|
by: Tinku |
last post by:
#include<stdio.h>
main()
{
char line;
scanf("%", line);
printf("%s", line);
}
it will read and print the line but what is "%" in general we
gives %s, %c .
|
by: Charles Arthur |
last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
|
by: ryjfgjl |
last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
|
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
|
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...
|
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...
|
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...
|
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...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
| |