Reputation: 909
// get user's input
int ch = getch();
switch (ch)
{
//input a number
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
{
int i = atoi(ch);
g.board[g.y][g.x] = i;
}
}
In the code I was given to add on to, ch was declared as an int. However, the function getch saves input as a string, correct? How can I convert the string ch into an int so I can work with it? I tried to use the atoi() function, but I keep getting these error messages.
sudoku.c: In function 'main':
sudoku.c:247:17: error: passing argument 1 of 'atoi' makes pointer from integer without a cast [-Werror]
/usr/include/stdlib.h:148:12: note: expected 'const char *' but argument is of type 'int'
sudoku.c:252:17: error: expected ';' before 'g'
sudoku.c:244:21: error: unused variable 'y' [-Werror=unused-variable]
cc1: all warnings being treated as errors
Upvotes: 2
Views: 11767
Reputation: 11
just subtract with '0' and it will automatically become an integer. The x is your variable
int x;
x=getch()-'0';
Upvotes: 1
Reputation: 1066
int i = atoi(ch);
replace this code below
int i = atoi((const char *)&ch);
you can find this with manual (Linux)
# man atoi
prototype is
#include <stdlib.h>
int atoi(const char *nptr);
Upvotes: -2
Reputation: 64098
atoi
expects a C-string (a \0
/nul terminated string). In your example you are passing it a single character.
Instead, utilize the benefits of the ASCII table layout:
/* Assuming (ch >= '0' && ch <= '9') */
int value = ch - '0';
/* Borrows from the fact that the characters '0' through '9' are laid
out sequentially in the ASCII table. Simple subtraction allows you to
glean their number value.
*/
Upvotes: 1
Reputation: 755209
Try the following
int i = (int)((char)ch - '0');
The numbers 0-9 are laid out in ascending order in terms of character codes. Hence subtracting '0' from the char
value will produce an offset that is equal to the actual number in question
Upvotes: 3
Reputation: 182674
the function getch saves input as a string, correct?
No, getch
reads a character and returns an int (you did correctly define ch
as int
). The easiest way to convert it to a real integer is to subtract '0'
. So after validating getch
, you can replace most of your code with:
if (isdigit(ch))
g.board[g.y][g.x] = ch - '0';
Upvotes: 7