-
Problem using getchar
Hello,
On my program I have 9 char named c1,...c9.
During the program, I write: gtch=getchar() (I should give a number between 1 and 9)
How can I modifiy the "value" of the character c1,...9 according to what number I enter?
For example, c4= 'x'. Then, I enter the number 4, so gtch='4'. How can I transform c4 to 'y'.
PS: I'm a begginer on C...
Thank you !
-
> On my program I have 9 char named c1,...c9.
Rather than doing
c1, c2, c3 etc
you use an array instead.
This gets you 9 chars labelled c[0] to c[8];
So perhaps for an easier life in this case
This gets you 10 chars labelled c[0] to c[9];
> During the program, I write: gtch=getchar() (I should give a number between 1 and 9)
This will get you a character '1' to '9'
To transform a single digit character containing a number into an integer, all you do then is
gtch = gtch - '0';
You can then do
c[gtch] = 'y';
-
Thank you for your quick answer !
I still have a small error:
Here's what I write (whithout details):
Code:
char cases[10]={'x0','x1',...'x9'};
int main (void)
...
char gtch;
gtch=getchar();
gtch=gtch-'0';
cases[gtch]='y'; --> in this line I have an error: array suscrpit has type char , so when I run my program no 'y' is visible.
Thank you for your time !
-
Well getchar() actually returns an int, so you should really have
Code:
int gtch;
gtch=getchar();
if ( gtch != EOF ) {
gtch=gtch-'0';
cases[gtch]='y';
}
Also, things like 'x0' are not characters, since you have two chars between single quotes.
-
I understand the problem, Thank you !:)