convert int to char

D

Drew

Hi All:

I know I am missing something easy but I can't find the problem! I
have a program which reads an integer as input.

The output of the program should be the sum of all the digits in the
integer that was entered.

So, if 353 was entered, the output should be 11.

I'm reading an integer, converting it to a string called intstring
with sprintf.

I'm then getting the length of the string and going thru a while loop
using that. Each time thru the while loop, I stuff the current
character of the string into a char variable ch.

Then I attempt to convert the character into an integer using atoi and
the address of ch. I was thinking that should give me the int value
of the char.

Then, I'm just adding the current integer value to a running
accumulator. That should do it!

The problem appears to be in the y = atoi(&ch); statement.

Somehow, y is assigned in the first iteration 3354, when it should
just be 3. The correct result of 3 appears to get combined with the
integer I entered, 354. I can't figure out how this is happening!

Any help would be appreciated. I have to be missing something easy!

Thanks!
Drew

My debugging output looks like this:

Enter an integer: 354
string is 354
ch is 3
y is 3354

ch is 5
y is 5354

ch is 4
y is 4354

The sum of the digits of 354 is 13062


Here's my code:

#include <stdio.h>

int main()
{

int x, y, z;
char intstring[25];
char ch;
int intstring_length;
int running_sum;

printf("Enter an integer: ");
scanf("%d", &z);

sprintf(intstring, "%d", z);

intstring_length = strlen(intstring);


printf ("string is %s\n", intstring);
x = 0;
running_sum = 0;

while (x < intstring_length)
{
ch = intstring[x];
printf ("ch is %c\n",ch);


y = atoi(&ch);
printf ("y is %d\n\n", y);

running_sum = running_sum + y;

x = x + 1;
}

printf("The sum of the digits of %s is %d", intstring, running_sum);


} // END OF MAIN
 
X

Xavier

Drew said:
Hi All:

I know I am missing something easy but I can't find the problem! I
have a program which reads an integer as input.

The output of the program should be the sum of all the digits in the
integer that was entered.

So, if 353 was entered, the output should be 11.

I'm reading an integer, converting it to a string called intstring
with sprintf.

I'm then getting the length of the string and going thru a while loop
using that. Each time thru the while loop, I stuff the current
character of the string into a char variable ch.

Then I attempt to convert the character into an integer using atoi and
the address of ch. I was thinking that should give me the int value
of the char.

Then, I'm just adding the current integer value to a running
accumulator. That should do it!

The problem appears to be in the y = atoi(&ch); statement.
atoi is not standard c... compile with warnings...
you have probably no such fonction in your environnement...
Somehow, y is assigned in the first iteration 3354, when it should
if atoi does not exist... what is returned is undefined..
here it seems to return what your enter 354, first digit before
just be 3. The correct result of 3 appears to get combined with the
integer I entered, 354. I can't figure out how this is happening!

Any help would be appreciated. I have to be missing something easy!

Thanks!
Drew

My debugging output looks like this:

Enter an integer: 354
string is 354
ch is 3
y is 3354

ch is 5
y is 5354

ch is 4
y is 4354

The sum of the digits of 354 is 13062


Here's my code:

#include <stdio.h>
#include said:
int main()
{

int x, y, z;
char intstring[25];
char ch;
int intstring_length;
int running_sum;

printf("Enter an integer: ");
scanf("%d", &z);

sprintf(intstring, "%d", z);

intstring_length = strlen(intstring);


printf ("string is %s\n", intstring);
x = 0;
running_sum = 0;

while (x < intstring_length)
{
ch = intstring[x];
printf ("ch is %c\n",ch);


y = atoi(&ch);
printf ("y is %d\n\n", y);

running_sum = running_sum + y;

x = x + 1;
}

printf("The sum of the digits of %s is %d", intstring, running_sum);


} // END OF MAIN

you don't have to do such a job...
let s="274"
s[0]-'0' == 2,
s[1] - '0' == 7 ... and so on because digits are contiguous values

Xavier
Xavier
 
F

Flash Gordon

Drew wrote:

I'm then getting the length of the string and going thru a while loop
using that. Each time thru the while loop, I stuff the current
character of the string into a char variable ch.

Then I attempt to convert the character into an integer using atoi and
the address of ch. I was thinking that should give me the int value
of the char.

Then, I'm just adding the current integer value to a running
accumulator. That should do it!

The problem appears to be in the y = atoi(&ch); statement.

It is. atoi is for converting a *string* in to an int, ch is a single
character. If fact, converting a single digit is far simpler:
y = ch - '0';

Here's my code:

#include <stdio.h>

int main()

int main(void) would be better. Always be specific under some conditions
it helps the compiler catch errors for you.
{

int x, y, z;
char intstring[25];
char ch;
int intstring_length;
int running_sum;

printf("Enter an integer: ");

Not guaranteed to be printed before waiting for input (line buffering is
common) so you need:
fflush(stdout);
scanf("%d", &z);

*always* check the return value of scanf, you have a problem if the
user does not enter a valid number. Or, better yet, you fgets to read a
line then parse it. Or even, in this case, don't bother converting it to
a number and work directly on the string the user enters!
sprintf(intstring, "%d", z);

intstring_length = strlen(intstring);


printf ("string is %s\n", intstring);
x = 0;
running_sum = 0;

while (x < intstring_length)
{
ch = intstring[x];
printf ("ch is %c\n",ch);


y = atoi(&ch);

y = ch - '0';
printf ("y is %d\n\n", y);

running_sum = running_sum + y;

x = x + 1;
}

printf("The sum of the digits of %s is %d", intstring, running_sum);

You need to terminate the last line of output with a line feed or there
is no guarantee it will actually be displayed.
} // END OF MAIN

Don't use // style comments on news groups, they don't survive line
wrapping. Also, they are not part of C89 which is the commonly
implemented C standard, only in C99, and why limit portability for this
little convenience?
 
K

Keith Thompson

Xavier said:
Drew wrote: [...]
The problem appears to be in the y = atoi(&ch); statement.
atoi is not standard c... compile with warnings...
you have probably no such fonction in your environnement...

atoi is standard C; see C99 7.20.1.2. (Its behavior is defined in
terms of strtol(), except on errors.)

I think the real problem is that atoi's argument is a pointer to a
string. atoi(&ch), if ch is an object of type char, will look at the
value of ch and whatever garbage happens to follow it in memory; if
that garbage happens to look like decimal digits, odd things will
happen. In fact, it's undefined behavior.
 
K

Keith Thompson

Flash Gordon said:
Drew wrote: [...]
The problem appears to be in the y = atoi(&ch); statement.

It is. atoi is for converting a *string* in to an int, ch is a single
character. If fact, converting a single digit is far simpler:
y = ch - '0';
[...]

And it's important to mention that this is true *only* because the
standard specifically guarantees that the digit characters '0' .. '9'
have consecutive and increasing numeric values. (There's no such
guarantee for letters, for example.)
 
J

Joe Wright

Drew said:
Hi All:

I know I am missing something easy but I can't find the problem! I
have a program which reads an integer as input.

The output of the program should be the sum of all the digits in the
integer that was entered.

So, if 353 was entered, the output should be 11.

I'm reading an integer, converting it to a string called intstring
with sprintf.

I'm then getting the length of the string and going thru a while loop
using that. Each time thru the while loop, I stuff the current
character of the string into a char variable ch.

Then I attempt to convert the character into an integer using atoi and
the address of ch. I was thinking that should give me the int value
of the char.

Then, I'm just adding the current integer value to a running
accumulator. That should do it!

The problem appears to be in the y = atoi(&ch); statement.

Somehow, y is assigned in the first iteration 3354, when it should
just be 3. The correct result of 3 appears to get combined with the
integer I entered, 354. I can't figure out how this is happening!

Any help would be appreciated. I have to be missing something easy!

Thanks!
Drew

My debugging output looks like this:

Enter an integer: 354
string is 354
ch is 3
y is 3354

ch is 5
y is 5354

ch is 4
y is 4354

The sum of the digits of 354 is 13062


Here's my code:

#include <stdio.h>

int main()
{

int x, y, z;
char intstring[25];
char ch;
int intstring_length;
int running_sum;

printf("Enter an integer: ");
scanf("%d", &z);

sprintf(intstring, "%d", z);

intstring_length = strlen(intstring);


printf ("string is %s\n", intstring);
x = 0;
running_sum = 0;

while (x < intstring_length)
{
ch = intstring[x];
printf ("ch is %c\n",ch);


y = atoi(&ch);
printf ("y is %d\n\n", y);

running_sum = running_sum + y;

x = x + 1;
}

printf("The sum of the digits of %s is %d", intstring, running_sum);


} // END OF MAIN

Maybe this?

/* I named this drew.c */
#include <stdio.h>
#include <stdlib.h>

void usage(void) {
puts("usage: drew <353>"), exit(0);
}

int main(int argc, char *argv[]) {
int sum = 0, ch;
char *arg = argv[1];
if (argc != 2) usage();
while ((ch = *arg++)) {
sum += ch - '0';
}
printf("%d\n", sum);
return 0;
}
 
M

Micah Cowan

Drew said:
Hi All:

I know I am missing something easy but I can't find the problem! I
have a program which reads an integer as input.

The output of the program should be the sum of all the digits in the
integer that was entered.

So, if 353 was entered, the output should be 11.

I'm reading an integer, converting it to a string called intstring
with sprintf.

That's a lot of work. It was a string in the first place, if you're
reading it from a text stream. Why not just use that?

Also, it would not be necessary, strictly speaking, to convert the
number to a string in order to add the digits together. But that is
one way to do it.
I'm then getting the length of the string and going thru a while loop
using that. Each time thru the while loop, I stuff the current
character of the string into a char variable ch.

Then I attempt to convert the character into an integer using atoi and
the address of ch. I was thinking that should give me the int value
of the char.

Bad idea. atoi() is /only/ used for converting /strings/, not
characters. You could construct a string using that character; but ch
in fact already /has/ an integer value; and if it is a digit in the
range of '0' through '9', then you can find out what number that digit
represents by simply subtracting the numeric value of the character
'0' from it.
Then, I'm just adding the current integer value to a running
accumulator. That should do it!

The problem appears to be in the y = atoi(&ch); statement.

Yeah. That figures. Because &ch is not a string. Anything could happen.
Somehow, y is assigned in the first iteration 3354, when it should
just be 3. The correct result of 3 appears to get combined with the
integer I entered, 354. I can't figure out how this is happening!

Like I said, anything could happen.
Here's my code:

#include <stdio.h>

int main()
{

int x, y, z;
char intstring[25];
char ch;
int intstring_length;
int running_sum;

printf("Enter an integer: ");

Since you don't terminate in a newline, and don't explicitly fflush(),
the above line may not show up on some systems before the scanf() gets
run. Thus, it may expect you to start typing things, without having
told you yet what it wants. To remedy this, you should put

fflush(stdout);

here.
scanf("%d", &z);

sprintf(intstring, "%d", z);

What if the user types in "asdk"?

Also, you could substitute

scanf("%24s", intstring);

to read the string in directly. You'd still probably want to do some
checking to make sure that it's actually numeric.
intstring_length = strlen(intstring);


printf ("string is %s\n", intstring);
x = 0;
running_sum = 0;

while (x < intstring_length)

You could use

while (intstring[x] != '\0')

in which case, you don't need intstring_length or the call to strlen().
{
ch = intstring[x];
printf ("ch is %c\n",ch);


y = atoi(&ch);

Use
y = ch - '0'

....but first said:
printf ("y is %d\n\n", y);

running_sum = running_sum + y;

If you type in a really long string, running_sum could
overflow. This isn't going to happen on the short little string
you've provided; but it's still worth making a habit of checking for.

If you #include <limits.h>, then

if (INT_MAX - running_sum < y)

it would overflow.
x = x + 1;

In C, it is /much/ more idiomatic to use the ++ operator.
++x;
or
x++;
}

printf("The sum of the digits of %s is %d", intstring, running_sum);

You forgot a newline.
 
C

code break

Why u made code so complicated .
Here the code which does same job.
main()
{
int num,sum,rem=0;
printf("Enter the valid number\n");
scanf("%d",&num);
while(num!=0)
{
rem=num%10;
sum+=rem;
num=num/10;
}
printf("The sum of digit is %d for %d",sum,num);
}
 
C

CBFalconer

Drew said:
I know I am missing something easy but I can't find the problem!
I have a program which reads an integer as input.

The output of the program should be the sum of all the digits in
the integer that was entered.

.... snip much ...

Yup. You are constructing large mountains out of teeny moleholes.

Try the following:

#include <stdio.h>
#include <ctype.h>

int main(void) {

int ch, sum;

printf("Enter a number: "); fflush(stdout);
sum = 0;
while (' ' == ch = getchar()) continue; /* absorb blanks */
while (isdigit(ch)) {
sum = sum + (ch - '0'); /* could be simpler coded */
ch = getchar();
}
printf("%d\n", sum);
return 0;
} /* untested */

--
"If you want to post a followup via groups.google.com, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
More details at: <http://cfaj.freeshell.org/google/>
Also see <http://www.safalra.com/special/googlegroupsreply/>
 
M

Martin Ambuhl

Drew said:
Hi All:

I know I am missing something easy but I can't find the problem! I
have a program which reads an integer as input.

The output of the program should be the sum of all the digits in the
integer that was entered.

So, if 353 was entered, the output should be 11.

#include <stdio.h>
#include <string.h>

int main(void)
{
char *src[] = { "353\n", "3354\n", "354\n" }, *nl, *sp;
size_t i, n = sizeof src / sizeof *src;
unsigned sum;

/* Input from the keyboard can be done with a while loop using fgets
to some buffer, the name of which replaces the src[]. */
for (i = 0; i < n; i++) {
if ((nl = strchr(src, '\n')))
*nl = 0;
for (sp = src, sum = 0; *sp; sp++) {
if (*sp < '0' || *sp > '9') {
printf("Found '%c', quiting with ...", *sp);
break;
}
sum += *sp - '0';
}
printf("For \"%s\", the sum of digits is %u\n", src, sum);
}
return 0;
}


For "353", the sum of digits is 11
For "3354", the sum of digits is 15
For "354", the sum of digits is 12
 
M

Micah Cowan

code break said:
Why u made code so complicated .
Here the code which does same job.
main()

Please use:

int main(void)

implicit int has been removed from C; and () is not the same as (void).
{
int num,sum,rem=0;
printf("Enter the valid number\n");

Since there's no formatting here, you could use puts() to do this
(just a style thang said:
scanf("%d",&num);

If someone enters a value greater than INT_MAX (or smaller than
INT_MIN), you get undefined behavior (bad).
while(num!=0)
{
rem=num%10;
sum+=rem;
num=num/10;

or: num/=10;
}
printf("The sum of digit is %d for %d",sum,num);

You forgot the final newline here. Also, num is guaranteed to be
0 at this point. Guess you didn't test it. :)

You forgot to return an int here:

return 0;

--------------------
#include <ctype.h>
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>

#define GOOD 0
#define BAD -1
#define BASE_DECIMAL 10

int get_uint(unsigned int *u)
{
char buf[40];
char *s = fgets(buf, sizeof buf, stdin), *t;
int retval = GOOD;
unsigned long ul;

if (s == NULL) {
/* Problem reading from stdin: bail. */
puts("\nI'm sorry; I couldn't read from standard input.");
exit(EXIT_FAILURE);
}

/* Skip initial ws. */
while (isspace(*(unsigned char*)s))
++s;

/* Read number. */
errno = 0;
ul = strtoul(s, &t, BASE_DECIMAL);
if (s == t) {
/* First non-ws char was not a digit. */
retval = BAD;
} else if (ul > UINT_MAX
|| ul == ULONG_MAX && errno == ERANGE) {
puts("Sorry; that number is too big for me.");
retval = BAD;
} else {
s = t;
/* Skip the rest of the whitespace. */
while (isspace(*(unsigned char*)s))
++s;
if (*s != '\0') {
puts("There was some garbage at the end of that line.");
retval = BAD;
} else {
*u = ul;
}
}

return retval;
}

int main(void)
{
unsigned int num, save, sum = 0;
int result;

/* Get a number from the user. */
do {
fputs("Please enter a valid number: ", stdout);
fflush(stdout);
result = get_uint(&num);
} while (result != GOOD);

save = num;
while (num != 0) {
div_t d = div(num, 10);
num = d.quot;
sum += d.rem;
/* Earlier in thread I said you should check for overflow. Of
* course, it hadn't yet occurred to me that overflow is truly
* impossible in this situation: the result will always be less
* than the original uint, which is already known to be valid. */
}

printf("The sum of digits for %u is %u.\n", save, sum);

return EXIT_SUCCESS;
}
--------------------
For completeness, you could check the return values of printf() and
puts(); etc. But I figure you'll notice that something was wrong when
nothing is printed...

-Micah
 
D

Dave Thompson

Why u made code so complicated .
Here the code which does same job.

Not really.

Aside: int main (void) is better; at least the int is required in C99.
{
int num,sum,rem=0;

You need to initialize sum to zero, but don't need to initialize rem.
printf("Enter the valid number\n");
scanf("%d",&num);

Calling either printf or scanf without a correct (variadic) prototype
while(num!=0)
{
rem=num%10;
sum+=rem;
num=num/10;
}
printf("The sum of digit is %d for %d",sum,num);

What value do you think this will print for num?

Nit: On some systems if the last (or as here only) output line doesn't
end with a newline \n it doesn't work.

- David.Thompson1 at worldnet.att.net
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,228
Members
46,818
Latest member
SapanaCarpetStudio

Latest Threads

Top