0
// 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;

            }
}

追加するように指定されたコードでは、chはintとして宣言されていました。ただし、関数getchは入力を文字列として保存しますよね?文字列chをintに変換して、それを操作できるようにするにはどうすればよいですか?atoi()関数を使おうとしましたが、これらのエラーメッセージが表示され続けます。

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
4

4 に答える 4

6

関数 getch は入力を文字列として保存しますよね?

いいえ、getch文字を読み取り、int を返します (正しく として定義chしましたint)。それを実数に変換する最も簡単な方法は、 を引くこと'0'です。したがって、検証後getch、ほとんどのコードを次のものに置き換えることができます。

if (isdigit(ch))
    g.board[g.y][g.x] = ch - '0';
于 2012-07-10T18:01:27.837 に答える
3

以下を試してください

int i = (int)((char)ch - '0');

文字コードの昇順で0~9の数字が並んでいます。したがって、char値から「0」を減算すると、問題の実際の数値に等しいオフセットが生成されます

于 2012-07-10T18:01:46.977 に答える
1

atoiC 文字列 ( \0/nul で終了する文字列) が必要です。あなたの例では、単一の文字を渡しています。

代わりに、ASCII テーブル レイアウトの利点を利用してください。

/* 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.
 */
于 2012-07-10T18:01:47.020 に答える
-1
        int i = atoi(ch);

以下のコードを置き換えます

int i = atoi((const char *)&ch);

これは手動で見つけることができます(Linux)

# man atoi

プロトタイプは

#include <stdlib.h>

int atoi(const char *nptr);
于 2012-07-10T18:14:17.650 に答える