473,698 Members | 2,051 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Is there a better way for scanf?

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!

Nov 14 '05 #1
11 2907

"QQ" <ju****@yahoo.c om> wrote in message
news:11******** *************@g 44g2000cwa.goog legroups.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
Nov 14 '05 #2
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

Nov 14 '05 #3
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

Nov 14 '05 #4
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

Nov 14 '05 #5
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

Nov 14 '05 #6
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

Nov 14 '05 #7
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);

Nov 14 '05 #8
"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
Nov 14 '05 #9
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
Nov 14 '05 #10

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

Similar topics

3
1625
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 DISPLAY SIX EVEN NUMBERS*/ #include<stdio.h>
4
1476
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: First posted on 21/12/03 one of the replys Wrote:
14
2732
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 problems with "%c" or is it the operating system I'm using? 1 #include <stdio.h> 2 3 int main()
7
7657
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 scanf cannot fill any fields it returns EOF. I have run some tests on scanf and, so far, I've not found an EOF return. For example: If the programer formats scanf for an int or
4
17190
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
5
1287
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?
14
13797
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*/ printf("%c\n",a);
10
1471
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. -------------------------------------------------------------------------------------------- Here's my solution #include <stdio.h>
3
9835
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 .
0
8671
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8598
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9152
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
7709
agi2029
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6515
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5858
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4613
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3037
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2321
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.