473,320 Members | 1,802 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,320 software developers and data experts.

%[^a] in scanf

main()
{
char str[20];
printf("Enter a string: ");
scanf("%[^a]",str);
printf("%[^a]",str);
}

Can some one help me with this code?
when i tried to execute this..... it reads the string untill character
' a ' and copies to str.
after 'a' everything else we type is discarded.
where can this be used? how exactly it is working?
is it making ^ operation on read data and when 'a' is pressed the ^
operation value turns out to be 0 which is string termination. is it
so? can i use other operators also instead of ^?
will it work on int and other data types?
whats the use of %[^a] in printf?

Thanks in advance....
Vamshi.

Nov 22 '06 #1
7 4844
"vamshi" <te*********@gmail.comwrote:
main()
{
char str[20];
printf("Enter a string: ");
scanf("%[^a]",str);
printf("%[^a]",str);
}

Can some one help me with this code?
Sure. First, remove the bugs. This includes at the very least 1.
#including relevant headers and 2. not reading random-length input into
fixed-length arrays. Fixing the declaration of main() would also be
good.
when i tried to execute this..... it reads the string untill character
' a ' and copies to str.
after 'a' everything else we type is discarded.
Yes... what did you expect? You are asking scanf() to match a scanset
that consists of any number of characters not from the list "a". And
that's what it's doing.
is it making ^ operation on read data
Not at all. The ^ operator and the ^ in the scanset conversion specifier
have no more to do with one another than the % operator and the % in
conversion specifiers...
can i use other operators also instead of ^?
....so no, you can't...
will it work on int and other data types?
....and no, it won't.

Look up the *scanf() functions in your C textbook, and find where it
explains the [] conversion specifier. It's quite useful, and any halfway
decent book on C should explain it.
whats the use of %[^a] in printf?
Nothing. Using the [] specifier in printf() at all, with or without ^,
invokes undefined behaviour. So don't do that.

Richard
Nov 22 '06 #2
vamshi wrote:
main()
Use the canonical int main(void) or int main(int argc, char **argv).
{
char str[20];
printf("Enter a string: ");
Either end output with a newline or call fflush(stdout), or your prompt
is not guaranteed to appear.
scanf("%[^a]",str);
scanf() is second only to gets() in being unsuited for string input.
fgets() is better suited for this job. A function like CBFalconer's
ggets(), (search the group for source), is even better.
printf("%[^a]",str);
This evokes undefined behaviour.
}

Can some one help me with this code?
when i tried to execute this..... it reads the string untill character
' a ' and copies to str.
after 'a' everything else we type is discarded.
Yes, that's what you've asked scanf() to do.
where can this be used?
Ideally nowhere.
how exactly it is working?
Implementation and platform specific. Ask in the appropriate group.
is it making ^ operation on read data
Not at all. scanf()'s ^ is totally different from the bitwise exclusive
OR operator.
and when 'a' is pressed the ^
operation value turns out to be 0 which is string termination. is it
so?
No, for heaven's sake, acquire almost any book on C and read it
through.
can i use other operators also instead of ^?
No, and in the context of scanf() ^ is not an operator.

Nov 22 '06 #3

Hi,
This is way of using scanf is called selection parsing.
which means that .. scanf("%[parsing chars]",);

now important points to be noted and let us learn by examples-
1) scanf("%[abcdefjh]",str);
With this scanf will accept only these characters which are present
in its search list.
suppose if we input--aejhxeb......so on.
result- here it will except only upto first illegal character is
encountered as per the searchlist.. so it willl accept
only..upto.."aejh" discarding all after that.

2) Now second way to use this search list technique called circumflex
method.
scanf("%[^abcdefjh]",str);
here the meaning is just reversed i.e it will accept all the
characters except those which are in the list.
suppose we input - xyzadayz..
result - here it will except only upto "xyz" becoz it
encounters 'a' which is illegal as per the search list

3) Comming to your queries.....
You have used the circmflex method now I think you understand it .
In printf it is not used.
for other datatypes it will work..but..be specific with your
Conversion Factors like.."%d...%s"..here we can see that no conversion
factors are being used which means that...it will work best for raw
types which is generally ASCII values..
So better to use it for string processing or only specific inputs you
required from the user..

now...here is a trick....scanf("%[^\n]",str); this will accept all the
keys....even space and tabs..also....expect..enter which willl
terminate it..and hence you can say that.....
from scanf you can also trap spacess.....

hope I answered your query...

shhnwz.a

Nov 22 '06 #4
santosh skrev:
vamshi wrote:
char str[20];
[...]
scanf("%[^a]",str);

scanf() is second only to gets() in being unsuited for string input.
scanf() can be difficult to use correctly for beginners,
OP's broken way can be fixed:

scanf("%19[^a]", str);

is "safe", since it will not overflow 'str'.

OP, might want to remove the end-of-record marker 'a', with:

scanf("%19[^a]", str);
getchar();

Furthermore, for robust code, the return value of scanf()
need to be checked (see below).
fgets() is better suited for this job.
Well, try to write this with fgets():

char line[81];
int n;

n = fscanf(stdin, "%80[^\n]%*[^\n]", line)
getchar(); /* throw away '\n' */

:-)

Above is a safe and simple way to read the first 80
char's of a line with unknown lenght. For error-checking,
we have:

case n == 1: line has been scanned
case n == 0: empty, i.e. no characters before '\n'
case n == EOF: EOF or I/O error before '\n', check with feof()/ferror()
A function like CBFalconer's ggets(), (search the group for source), is
even better.
Well, IIRC, ggets() used malloc/realloc, which I usually hate.
Wouldn't use it for cases where I need robust code. The
point is that ggets() is a potential DoS [1] security hole, since
it will grab all available memory...

R.H. fgetdata() has a 'maxrecsize' parameter, which makes
it more robust, see:

http://users.powernet.co.uk/eton/c/fgetdata.html

where can this be used?

Ideally nowhere.
I have used it and will continue to do so, for example:

fscanf(stdin,"%*[^\n]");

when I just want to "eat" until the end-of-line.
how exactly it is working?

Implementation and platform specific. Ask in the appropriate group.
AFAIK, the usage of circumflex (^) in a scanlist is
well-defined, it's rather the usage of (-) which is
implementation specific.

--
Tor
[1] DoS = Denial of Service

Nov 23 '06 #5

vamshi wrote:
main()
{
char str[20];
printf("Enter a string: ");
scanf("%[^a]",str);
printf("%[^a]",str);
}

Can some one help me with this code?
when i tried to execute this..... it reads the string untill character
' a ' and copies to str.
after 'a' everything else we type is discarded.
where can this be used? how exactly it is working?
is it making ^ operation on read data and when 'a' is pressed the ^
operation value turns out to be 0 which is string termination. is it
so? can i use other operators also instead of ^?
will it work on int and other data types?
whats the use of %[^a] in printf?

Thanks in advance....
Vamshi.
Nov 23 '06 #6
Thanks to all for clearing my doubts.

Regards,
Vamshi.

On Nov 22, 4:58 pm, "Shhnwz.a" <mshahnawaz...@gmail.comwrote:
Hi,
This is way of using scanf is called selection parsing.
which means that .. scanf("%[parsing chars]",);

now important points to be noted and let us learn by examples-
1) scanf("%[abcdefjh]",str);
With this scanf will accept only these characters which are present
in its search list.
suppose if we input--aejhxeb......so on.
result- here it will except only upto first illegal character is
encountered as per the searchlist.. so it willl accept
only..upto.."aejh" discarding all after that.

2) Now second way to use this search list technique called circumflex
method.
scanf("%[^abcdefjh]",str);
here the meaning is just reversed i.e it will accept all the
characters except those which are in the list.
suppose we input - xyzadayz..
result - here it will except only upto "xyz" becoz it
encounters 'a' which is illegal as per the search list

3) Comming to your queries.....
You have used the circmflex method now I think you understand it .
In printf it is not used.
for other datatypes it will work..but..be specific with your
Conversion Factors like.."%d...%s"..here we can see that no conversion
factors are being used which means that...it will work best for raw
types which is generally ASCII values..
So better to use it for string processing or only specific inputs you
required from the user..

now...here is a trick....scanf("%[^\n]",str); this will accept all the
keys....even space and tabs..also....expect..enter which willl
terminate it..and hence you can say that.....
from scanf you can also trap spacess.....

hope I answered your query...

shhnwz.a
Nov 23 '06 #7
Tor Rustad said:

<snip>
>
Well, IIRC, ggets() used malloc/realloc, which I usually hate.
Wouldn't use it for cases where I need robust code. The
point is that ggets() is a potential DoS [1] security hole, since
it will grab all available memory...

R.H. fgetdata() has a 'maxrecsize' parameter, which makes
it more robust, see:

http://users.powernet.co.uk/eton/c/fgetdata.html
Please don't use that URL. Instead, see:

http://www.cpax.org.uk/prg/writings/fgetdata.php

Thanks.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Nov 23 '06 #8

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

Similar topics

12
by: B Thomas | last post by:
Hi, I was reading O'Reilly's "Practical C programming" book and it warns against the use of scanf, suggesting to avoid using it completely . Instead it recomends to use using fgets and sscanf....
14
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...
7
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...
4
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
17
by: Lefty Bigfoot | last post by:
Hello, I am aware that a lot of people are wary of using scanf, because doing it improperly can be dangerous. I have tried to find a good tutorial on all the ins and outs of scanf() but been...
33
by: Lalatendu Das | last post by:
Dear friends, I am getting a problem in the code while interacting with a nested Do-while loop It is skipping a scanf () function which it should not. I have written the whole code below. Please...
14
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*/...
8
by: Neil | last post by:
Hello Just to let you know this not homework, I'm learning the language of C on my own time.. I recently tried to create a escape for user saying printf ("Do you want to continue? (y or n)");...
3
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 .
2
by: subramanian100in | last post by:
Consider the following program named as x.c #include <stdlib.h> #include <stdio.h> int main(void) { unsigned int u; char str;
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

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.