473,326 Members | 2,090 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,326 software developers and data experts.

Some logic error in my C code

Raj
Following is a code to print integer equivalent of a hexadecimal
number. If the entered number starts with a 0x or a 0X, calculation is
done after skipping these two characters. Now, this code works fine
except when i enter 0 as the 1st element & then follow it up with a
non 'x' or non 'X' character.
For e.g. When i enter 09, i get output 0... not only this, if i start
my input with a 0, then output always comes out to be 0. Otherwise the
code works fine. If anybody can help... thanx!

Code:

#include<stdio.h>
int main(void)
{
int n=0,i=0,c;
clrscr();
printf("Enter hexadecimal string\n");
while((c=getchar())!=EOF){
if(c=='0'){
if(i==0)
if(((c=getchar())=='x')||((c=getchar())=='X'))
continue;
}
i++;
if(c>=48&&c<=57)
n=16*n+(c-48);
else if(c>=65&&c<=70)
n=16*n+(c-65)+10;
else if(c>=97&&c<=102)
n=16*n+(c-97)+10;
}
printf("Corresponding integer value is: %d",n);
getch();
return 0;
}

Aug 25 '07 #1
4 1722

"Raj" <za*****@gmail.comwrote in message
news:11**********************@q3g2000prf.googlegro ups.com...
Following is a code to print integer equivalent of a hexadecimal
number. If the entered number starts with a 0x or a 0X, calculation is
done after skipping these two characters. Now, this code works fine
except when i enter 0 as the 1st element & then follow it up with a
non 'x' or non 'X' character.
For e.g. When i enter 09, i get output 0... not only this, if i start
my input with a 0, then output always comes out to be 0. Otherwise the
code works fine. If anybody can help... thanx!

Code:

#include<stdio.h>
int main(void)
{
int n=0,i=0,c;
clrscr();
printf("Enter hexadecimal string\n");
while((c=getchar())!=EOF){
if(c=='0'){
if(i==0)
if(((c=getchar())=='x')||((c=getchar())=='X'))
You've fallen victim to intelligent or guarding.
If c == 'x', the program knows that it must execute the "continue". So the
second half of the expression is never executed. If c does not equal x,
getchar() is aclled for a second time.
>
continue;
}
i++;
if(c>=48&&c<=57)
n=16*n+(c-48);
else if(c>=65&&c<=70)
n=16*n+(c-65)+10;
else if(c>=97&&c<=102)
n=16*n+(c-97)+10;
}
printf("Corresponding integer value is: %d",n);
getch();
return 0;
}
Replace all this logic with a call to isxdigit() to make sure you input is
valid
and wrap it up in a function

int xdigittoval(char ch)
{
static char *digits = "0123456789abcdef";
ch = tolower(ch);
assert(isxdigit((unsigned char) ch));
return strchr(digits, ch) - digits;
}

I apologise for the cast to unsigned char. Just a quirk of the standard. It
should never trigger anyway, but belt and braces is a good policy. Now you
don't need those error-prone and possibly non-portable ASCII values.

--
Free games and programming goodies.
http://www.personal.leeds.ac.uk/~bgy1mm

Aug 25 '07 #2
Raj
On Aug 25, 5:54 pm, "Malcolm McLean" <regniz...@btinternet.comwrote:
"Raj" <zape...@gmail.comwrote in message

news:11**********************@q3g2000prf.googlegro ups.com...
Following is a code to print integer equivalent of a hexadecimal
number. If the entered number starts with a 0x or a 0X, calculation is
done after skipping these two characters. Now, this code works fine
except when i enter 0 as the 1st element & then follow it up with a
non 'x' or non 'X' character.
For e.g. When i enter 09, i get output 0... not only this, if i start
my input with a 0, then output always comes out to be 0. Otherwise the
code works fine. If anybody can help... thanx!
Code:
#include<stdio.h>
int main(void)
{
int n=0,i=0,c;
clrscr();
printf("Enter hexadecimal string\n");
while((c=getchar())!=EOF){
if(c=='0'){
if(i==0)
if(((c=getchar())=='x')||((c=getchar())=='X'))

You've fallen victim to intelligent or guarding.
If c == 'x', the program knows that it must execute the "continue". So the
second half of the expression is never executed. If c does not equal x,
getchar() is aclled for a second time.


continue;
}
i++;
if(c>=48&&c<=57)
n=16*n+(c-48);
else if(c>=65&&c<=70)
n=16*n+(c-65)+10;
else if(c>=97&&c<=102)
n=16*n+(c-97)+10;
}
printf("Corresponding integer value is: %d",n);
getch();
return 0;
}

Replace all this logic with a call to isxdigit() to make sure you input is
valid
and wrap it up in a function

int xdigittoval(char ch)
{
static char *digits = "0123456789abcdef";
ch = tolower(ch);
assert(isxdigit((unsigned char) ch));
return strchr(digits, ch) - digits;

}

I apologise for the cast to unsigned char. Just a quirk of the standard. It
should never trigger anyway, but belt and braces is a good policy. Now you
don't need those error-prone and possibly non-portable ASCII values.

--
Free games and programming goodies.http://www.personal.leeds.ac.uk/~bgy1mm- Hide quoted text -

- Show quoted text -- Hide quoted text -

- Show quoted text -
Corrected the error...Thanx so much!!

Aug 25 '07 #3
Raj wrote:
Following is a code to print integer equivalent of a hexadecimal
number.
Why aren't you using `strtol` after reading the characters in?
If the entered number starts with a 0x or a 0X, calculation is
done after skipping these two characters. Now, this code works fine
except when i enter 0 as the 1st element & then follow it up with a
non 'x' or non 'X' character.
For e.g. When i enter 09, i get output 0... not only this, if i start
my input with a 0, then output always comes out to be 0. Otherwise the
code works fine. If anybody can help... thanx!

Code:

#include<stdio.h>
int main(void)
{
int n=0,i=0,c;
clrscr();
Non-Standard, undeclared, and unnecessary. Bin it.
printf("Enter hexadecimal string\n");
while((c=getchar())!=EOF){
if(c=='0'){
if(i==0)
if(((c=getchar())=='x')||((c=getchar())=='X'))
If the next character isn't 'x', it will compare the
/second next/ character with 'X'. So if the first
character is 'X', it will read another character to
see if it's 'x'.
continue;
}
i++;
What's `i` for? Nothing. Bin it.
if(c>=48&&c<=57)
You must be out of your mind. What are `48` and `57`,
n=16*n+(c-48);
else if(c>=65&&c<=70)
`65` and `70`,
n=16*n+(c-65)+10;
else if(c>=97&&c<=102)
`97` and `102` supposed to be?

If you're going to assume the character set is ascii, then
at least use character constants and comment your assumptions.
If not, use a portable and straightforward way -- I can think
of two while I'm still typing -- to translate a hex character
into the corresponding hex value.
n=16*n+(c-97)+10;
}
printf("Corresponding integer value is: %d",n);
getch();
return 0;
}
--
Runs From Trolls Hedgehog
Scoring, bah. If I want scoring I'll go play /Age of Steam/.

Aug 25 '07 #4
"Malcolm McLean" <re*******@btinternet.comwrites:
[...]
assert(isxdigit((unsigned char) ch));
[...]
>
I apologise for the cast to unsigned char. Just a quirk of the
standard. It should never trigger anyway, but belt and braces is a
good policy. Now you don't need those error-prone and possibly
non-portable ASCII values.
Good grief, don't apologize for writing correct code.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Aug 25 '07 #5

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

Similar topics

53
by: Cardman | last post by:
Greetings, I am trying to solve a problem that has been inflicting my self created Order Forms for a long time, where the problem is that as I cannot reproduce this error myself, then it is...
3
by: Mike | last post by:
Hey guys I am pulling my hair out on this problem!!!!! Any help or ideas or comments on how to make this work I would be grateful! I have been working on this for the past 4 days and nothing I do...
0
by: Tony Johansson | last post by:
Hello Experts! I reading a book called programming with design pattern revealed by Tomasz Muldner and here I read something that sound strange. "Exception are divided into logic errors and...
193
by: Michael B. | last post by:
I was just thinking about this, specifically wondering if there's any features that the C specification currently lacks, and which may be included in some future standardization. Of course, I...
2
by: Josef Meile | last post by:
Hi, I have this constructor: public CExcelDatabase(string host, string user, string password, string database, bool promptCredentials, int findExcelInstance, bool readOnly) { //Some code...
4
by: Steve | last post by:
I have read a couple articles online, read my Jesse Liberty book but I am still confused as to just what the best practices are for using exceptions. I keep changing how I'm working with them and...
4
by: jej1216 | last post by:
I have a PHP page that displays in a table budget vs. actual figures from a MySQL db. I want to add logic where if the actual is greater than the budget, the data is displayed in red, otherwise...
7
by: hutch75 | last post by:
Hi Folks, Wondering if my logic is bringing me down the right path..was hoping for some feedback before I spend too much time creating the source document / database to test it out. At a high...
4
by: Sheldon | last post by:
Hi, I have a unique case where I need an array of structs that grows and within this array is another struct that grows in some cases. I'm having trouble allocating memory. Since I have never...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
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...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
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...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...

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.