Arrays!

Hi, i have been trying to get my head around arrays.

Here:
I define a variable
char input[3];

Then take input
cin.getline(input,3);

An 'add' function then adds the 1st and 3rd indexes
cout << add(input[1], input[3]);

My Question is, how can i take input with numbers AND char's into an array?

P.s: Input would be something like: 1,2

Thanks.
Last edited on
A simple array is one type only. An array of char, or an array of int (or an array of some other type). You cannot mix them up together. You cannot have an array in which some of the elements are meant for int values, and some are meant for char values.

If you insist on using an array to store both char and int together, you might consider making a new structure that contains a char and an int, and then making an array of those structures. You would then write each char and int into these structures, within the array.


What are you trying to do? English isn´t my mother tongue, but I´d like to help you out.
Last edited on
Well i want to take in input and place it into an array but i want to take in input that is of two different types int and char. I wanted a way of solving this problem or at least some ideas about tackling it.
Last edited on
My Question is, how can i take input with numbers AND char's into an array?

P.s: Input would be something like: 1,2


Oh, I see.

I wanted a way of solving this problem or at least some ideas about tackling it.


Read in the chars, then take each one that is a digit and make an int based on that char.

If you have a char, named someChar for example, and you're absolutely certain it's a single digit (i.e. 0 to 9), you can turn it into an int like this:

int x = (int)someChar - 48;

I advise you to check that the char really is a digit from 0 to 9, though.

As you can see here, the character 0 has the actual numerical value of 48, so it you cast to an int, that int would have the value 48. Accordingly, if you subtract 48 from the character, you get the actual numerical value 0.
http://www.asciitable.com/

It's not the safest way to convert a char to an int. If you search, you'll find better.
Last edited on
Yeah, conversion was my initial thought, thanks for your help. :)
Topic archived. No new replies allowed.