Question

some basic question in C

Asked by: sanko50

hi, here i have some basic question

question1:  where i  should/must use unsigned integers/chars???
is it merely increases the data range ??

can you give a small SIMPLE CODE where unsigned integers/chars are really worthy than signed ???



question2:

in the format specifier of scanf()  what does percent(%) means??

is it necessary that there should be as many percent(%) that many data type character???

otherwise how this format works...

 sscanf(" \t test", "%*[ \t]%s", a)

what does this format do?? notice here there is two percent(%) but only one data type character(i.e  's')....it is peculiar to me.

or  syntax  "%8[^@]%*c" also works in the scanf() ....it seems that there is no  relation with percent(%) and data type character. is it true?????

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2004-01-27 at 06:32:45ID20864225
Tags

code

,

c

,

char

Topic

C Programming Language

Participating Experts
5
Points
30
Comments
15

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. sscanf with va_list
    Hi folks, Here is what I want to do void MySscanf( char* pcp_string, const char* pcp_format, ... ) { va_list marker; va_start( marker, pcp_format); sscanf(pcp_string, pcp_format, marker ); /* that is impossible :-( */ va_end( marker ); } As the prototype of...
  2. sscanf function in VB?
    Is there a function in VB that is simmilar to the C function sscanf?
  3. setlocale and sscanf
    setlocale changes the behaviour of sscanf (e.g. the way floats are decoded . vs ,). Is there any way to override this? I know how the text data files that I am reading are formatted. I don't want to temporarily change the setlocale during the sscanf operations since other thr...
  4. sscanf(), how to use / convert to c++?
    Hello, First, is there a new function in the C++ standard to replace the C function sscanf()? I've read about doing it with streams, but none of those sites came with any example or other type of further explanation. Second, why isn't the following working? I have a ...
  5. Sscanf problems :)
    Hey, just started on Visual C++, but I'm having some problems with sscanf and pattern matching in general :) Basically, what I need to do, is match ansi-colour codes and split up the string accordingly. I currently have this function: void CAMCView::OnRecieve(int nError...
  6. scanf briefing
    Hi, I'm just getting started in C and am aware that there are risks involved with using scanf and similar commands that expect a certain amount of data. I'd like to become familiar with not just the best way or most common way to avoid these problems but also to understan...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: stefan73Posted on 2004-01-27 at 07:29:52ID: 10210074

1. Signedness is a primarily matter of whether you need negative values or not. Using a sign halves your positive range, of course. But be careful when comparing signed and unsigned values.

2. It's a matter of match. '*' is a pseudo-data type character, it throws away the field, not storing it. So it doesn't need an argument afterwards. [] is the scanset, the set of allowed characters. So "%*[ \t] scans for a sequence of whitespace at line start.

 

by: KdoPosted on 2004-01-27 at 09:10:54ID: 10210929

Hi stefan73,

Signage comes into play in two areas of C.

If a value cannot be negative and might be a very large integer, unsigned is the way to go.


If you're converting (recasting) integer type data, the sign bit of the smaller field can really mess you up.

unsigned int BigValue;
char         SmallValue;

  SmallValue = 130;  /* generates compiler warning  */
  BigValue = (unsigned int)SmallValue;

You might think that BigValue is set to 130 (0x82).  It certainly makes sense.  But in fact BigValue is 0xFFFFFF82.  In recasting SmallValue, it is extended to 32 bits WITH SIGN EXTENSION.  Since it's negative, the 1 bit in the sign position propogates all the way to the top bit in BigValue.  The result is that BigValue is probably not the value that you want.


unsigned int  BigValue;
unsigned char SmallValue;

  SmallValue = 130;  /* generates compiler warning  */
  BigValue = (unsigned int)SmallValue;

This behaves exactly like you think it should.



Good Luck,
Kent

 

by: cofactorPosted on 2004-01-27 at 11:21:53ID: 10212147

hi  KDO

thanks for the explanation

i have some queries on your answer.

you started with the example   SmallValue = 130; ( 2byte in VC++)

when i am casting it into      unsigned int    the result should go to 4 byte( VC++) .

130 is positive....so  when i will caste it it will be a positive number.

so, if M.S.B  1 is -ve and 0 is positive then i should get  in the register like below

   0.....binary code of 130.(  total 32 bits)
M.S.B ... other bits  

why i would get  0xFFFFFF82 as a result?



i may be wrong ....can you tell whats wrong with this?

and about the second question
_________________________
as stefan73 told

* >> it skips or throws
 [\t] >> only tab(which contains 7 blank spaces)  are allowed.

 so  %*[ \t]  means it will skip 7 blank space while reading....is it correct?

what about  %8[^@]%*c  ? my probelm is how many percent sign i can give ?







 

 

by: cofactorPosted on 2004-01-27 at 11:26:42ID: 10212197


hi , i have changed mine account  to  cofactor ..... i am getting mails irregularly  in my old account(sanko50).

do i need to close my old account(sanko50) ???
thanks

 

by: KdoPosted on 2004-01-27 at 11:45:03ID: 10212369

Hi cofactor,

You should close your old account.  Or contact a moderator and ask him to transfer your history and close it for you.  (I'll miss 'sank050'!)


Does VC++ use two bytes to store a character?  My example shows converting from a char to an int and was meant to convert from 1 byte to 4.  This is something I have to do from time to time and have been bit by the sign bit more times than I care to admit.  It goes back to the old big-endian vs. little-endian argument.

Often time you'll get data from a source that might behave differently than the system under which you're currently running.  To write code that always handles the data correctly you sometimes have to pack/unpack the data yourself.  When that happens you run the risk of the problem that I described.

Here's two common places for this:

TCP/IP.  The network header contains the IP address.  It is always 4 bytes, left to right.  1.2.3.4 is stored as 0x01020304.  Extract those four bytes as a 32-bit integer on a big-endian system and the integer will contain 0x01020304.  Do so on a little endian system and you'll get 0x04030201.  The way to ensure that the C program will always assemble the correct value is to have the program build the integer byte by byte.

Data Storage.  The same principal applies here.  There are quite a few record formats where the record length is noted by a leading integer field.  The only way to ensure that your program will read the record correctly is to make sure that you interpret the integer correctly and that usually means assembling it yourself.


Good Luck,
Kent

 

by: PaulCaswellPosted on 2004-01-28 at 01:39:27ID: 10216745

sanko50/cofactor,

kdo has effectively covered signed/unsigned for you.

In VC++ 'char' is indeed a 16bit value and therefore does not have the same effect that kdo was describing. Using signed/unsigned is a good way of getting the compiler to find your errors for you. Using unsigned for a loop counter, for example will often highlight potential problems with array accessing for example. Code like:

extern char buffer[];
extern int x;

for ( int i = 0; i < 100; i++ )
{
   buffer[x-i] = ' '; // Oops! I meant to use 'x+i'
}

would probably not signal errors but

for ( unsigned int i = 0; i < 100; i++ )
{
   buffer[x-i] = ' '; // Oops! I meant to use 'x+i'
}

would probably generate a warning because you are mixing signed and unsigned values in the calculation.

Generally, if the data is unsigned, say so. If you are working with binary data, use unsigned; if you are working with decimal values, use signed. Even if your compiler does not help finding problems, at least your intent was clear for others to see when they read your code.

>> in the format specifier of scanf()  what does percent(%) means??

The '%' is a trigger for scanf to begin scanning for a description of the format to use for the following characters in the format string.

>> is it necessary that there should be as many percent(%) that many data type character???

No, as you have correctly shown in one of your examples below. Using a '*' in the format allows you to skip parts of the input data without storing anything.

>> otherwise how this format works...
>> sscanf(" \t test", "%*[ \t]%s", a)
>> what does this format do?? notice here there is two percent(%) but only one data type character(i.e  's')....it is peculiar to me.

The '%*[ \t]' says 'take as many spaces or tab characters ([ \t]) from the input string and throw them away (*).
The '%s' says take the next string (terminated by a space or end of string incidentally) and put it into the next parameter ('a' in this case so I hope its a pointer to a string).

>> or  syntax  "%8[^@]%*c" also works in the scanf()

This will read up to eight characters, stopping at the end of the string or the first '@' character and store them in the first parameter, then take the next character (the '@') and throw it away (*).

>> ....it seems that there is no  relation with percent(%) and data type character. is it true?????

The number of parameters should be the same as the number of '%'s in the format that are not followed by '*' or another '%'.

E.G. "%%%*d%d" only needs one prarmeter (for the final %d). The '%%' will expect a '%' character in the input string, the %*d will read and throw away a decimal number, the %d will read and store a decimal number.

>> * >> it skips or throws
>> [\t] >> only tab(which contains 7 blank spaces)  are allowed.
>> so  %*[ \t]  means it will skip 7 blank space while reading....is it correct?

The '\t' is not expanded into 7 spaces, it stays as a 'tab' character (0x09) and therefore skips tabs.


Paul

 

by: jhshuklaPosted on 2004-02-02 at 13:36:09ID: 10256077

i don't understand why would one need a signed char anyways. just to force the first bit to 0?

 

by: PaulCaswellPosted on 2004-02-03 at 01:25:30ID: 10259582

I agree, signed char's are an anachronism. They arise from the vagueness of the original definition of a char in C.

'int' came first when computers were expected to be used for primarily mathematical processes and calculations. When text processing became popular, the int was used as a character number from a list of possibles.

Then the dullards stepped in and tried to standardise these lists. There was 6bit TTS used on paper tapes, 7bit ASCII or 7bit EBCDIC used on punched cards etc etc. At a time when memory was expensive eight bits seemed a convenient packet to store all of these in.

With 6 or 7 bits there was no problem with the sign bit. Then extended ASCII - 8 bits - came along, opening up a can of worms. All sorts of problems arose that are still here today. I understand one moon-bound rocket exploded due to just such a problem. The retrofitted solution was to invent the concept of 'unsigned'. The problem was that the numerical distance between 'A' and 'Z' was, correctly, 26 but the distance between 'A' and the '<<' (spanish open quotes) is NEGATIVE.

And we still suffer from the two gremlins of 'unsigned' and 'Extended ASCII' to this day. Thank goodness ISO are finally baring their teeth at IBM et al and ignoring their demands to add more and more code pages. We are getting there. I look forward to the death of 'unsigned char'. Java has taken a significant step towards finally killing off this horrible accident waiting to happen but I dont feel it has solved the problem yet. Who knows what lies in the future.

 

by: stefan73Posted on 2004-02-03 at 02:24:29ID: 10259845

Yes, signs on a chars are definitely not necessary anymore, and the use of a "signed 8-bit integer" is probably limited to such esoteric things as 8-bit-relative assembly jumps. Unicode is definitely the future.

Speaking of java, the forced signedness of ints + longs there can be a pain when you want to use the '%' operator to transform an int to a limited number range without regard to the sign.

 

by: jhshuklaPosted on 2004-02-04 at 09:35:09ID: 10272967

yeah and java doesn't have bitwise access to ignore unimportant bits.
well we can't do anything abt it unless we r employed by IBM or Sun or Intel or ...

 

by: PaulCaswellPosted on 2004-02-05 at 01:12:59ID: 10278902

Yes we can!

We can create carefully crafted arguments for or against the issues we see in the tools that are provided for us. We can then present these arguments in a forum such as this where others can provide their input in the form of constructive criticism, as I am doing now for you. Ultimately, hopefully, someone will read our discourse and discuss it with someone who CAN change things.

In this way only will we progress. Defeatism will be defeated.

 

by: PaulCaswellPosted on 2004-03-03 at 04:01:12ID: 10503721

Sunnycoder,

You did note that the asker changed name to 'cofactor' mid-flow. Perhaps that stopped them receiving the informationals. There doesnt seem to be any more input from them after that.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...