I am very new at this, and I am sure this is a really basic question but if I don't know, then I have been taught to ask .... even if it is dumb.

Can a character be added to an interger. I feel confident I would get a syntax error, but wanted to make sure.

Can a character string like "215" be converted to an integer?

Charlie

It depends what language (C or C++) and what kind of error-checking you need.

A basic function which has no error-checking is atoi():

int myNumber;
myNumber = atoi(myString); // myString had better contain a number!

A better C function in regards to error-checking is strtol. For C++, you'll want to pop it in and out of a stream:

istringstream myStream;
myStream.str(myString);
myStream >> myNumber;

Just to nitpick a li'l: a char and a character string are very different. For a character string, you'll need to do like joeprogrammer says, which would be correct for your example. You can also add the value of a single character (char) to an integer, but remember that a char value is not necessarily it's integer representation. That is '0' != 0, '1' != 1, etc...

Just to nitpick a li'l: a char and a character string are very different. For a character string, you'll need to do like joeprogrammer says, which would be correct for your example. You can also add the value of a single character (char) to an integer, but remember that a char value is not necessarily it's integer representation. That is '0' != 0, '1' != 1, etc...

I assumed when he said, "Can a character string like "215" be converted to an integer" that he meant character string, regardless of the thread title.

However, Infarction is correct, for a char conversion, subtraction is all that is necessary:

int myNumber;
myNumber = myChar - '0'; // won't work for a string!

I am seeking clues in C
I'm Learning here ...... Don't give up on me yet.

How about in this case;

[
int A;
float B;
char C;

can the expression A+C*B

work?

I don't see how I can do it.

Charlie

>can the expression A+C*B work?
Sure. Convert C to an integer first.

float result;
int anotherInteger;
anotherInteger = C - '0';
result = A+anotherInteger*B;

If you didn't convert the char to an integer first, you'd get a much higher value than you expect.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.