wizardry100
08-20-2002, 03:59 AM
i wanted to ask if someone could tell me how i could assign assign variables to arrays by accepting user input and assigning this input to an array
eg.
program asks for an integer
this integer is stored as array[row][column]
i've tried
d= getchar()
array[r][c] = d
printf("%d",array[r][c])
but that doesnt seem to work
anyone have any ideas?
Iceplug
08-20-2002, 07:52 AM
I think that you'll have to convert your character into an integer before. What type is d and the array?
well, i've forgotten some of my c++ from last semester.... which is kinda bad since my next c++ course in, uhh, 3 weeks is coming up.... but.. hrm.....
1) are you only taking a single input, or a lot of them? if you are taking more than 1 you need a loop, incrimenting the position in the array the input gets stored at
we (i) havent learned about getchar(), or even printf() so ill just do this how i know and you can modify it
cout >> "Enter an integer: ";
cin >> d;
array[r][c]=d;
cout >> "/n/n%d " >> array[r][c];
that basically is what you already have, so it should work.
the only thing i can think of why its not working is the array[r][c]..... r and c must be for a loop, correct? .... might be something wrong there..
wizardry100
08-21-2002, 12:34 AM
ok to be more specific the
array is an int which takes in a row(int) and a column(int)
d would be an int
when i do this:-
# define MAX = 100
int array[MAX][MAX]
int row = 0, column =0
d= getchar()
array[row][column] = d
printf("%d",array[row][column])
i know the problem and it is that it keeps giving me the ascii equivalent...
so when i input 2 it stores 2 in ascii which is 50 (i think) and then it assigns 50 to array[row][column] so the output it prints is '50'.
I'm just not sure how to make it store as '2' instead of the ascii value of 2.
I've tried printf("%c",array[row][column])
and it works for numbers 0-9 but no numbers outside of these values work so '10' wouldnt work and 11 and so on
anybody know how to make it store as it's input value and not it's ascii value?
wizardry100
08-21-2002, 12:36 AM
oh forgot to add
Cert: its just C not C++ hehe and i know how to make it work for a loop it just doesnt store the data i want it to store
eg i want input 2 output 2
but what i get is input 2 output 50 (ascii)
Iceplug
08-21-2002, 06:58 AM
I think you're going to have to convert it with atoi.
reboot
08-21-2002, 07:57 AM
That's correct. c isn't vb. In "int d= getchar();", d isn't going to be what you are expecting...
DrunkenHyena
08-21-2002, 03:14 PM
getchar only returns a single char, so if your input is '42', getchar is going to give you '4'.
Try using gets which returns a string, then as mentioned already you'll need to use atoi to get it as an integer.
wizardry100
08-21-2002, 10:48 PM
ok! thanks for the replies
i understand how to do it now :)