作为一个整体,我对C和编程是个新手。我已经掌握了一个程序的基础知识,我正试图更好地掌握C语言,但在命令行从用户的args获取输入来填充我的数组时遇到了问题:
./sudoku.c "9...7...." "2...9..53" etc etc我已经使用我填充的数组测试了我的程序,它可以工作,但如果我不能接受用户输入,这是不好的。我的输入如下所示:
grid[9][9] = {{9, 0, 0, 0, 7, 0, 0, 0, 0},
{2, 0, 0, 0, 9, 0, 0, 5, 3}};有什么建议吗?
任何帮助都将不胜感激
发布于 2016-03-13 14:59:33
只要用简单的循环阅读即可。
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(int argc, char* argv[]) {
int grid[9][9];
int input_error = 0;
int i, j;
if (argc != 1 + 9) { /* check number of rows in input */
input_error = 1;
} else {
for (i = 0; i < 9; i++) { /* read each rows */
if (strlen(argv[i + 1]) != 9) { /* check number of cols in input */
input_error = 1;
break;
}
for (j = 0; j < 9; j++) { /* read each cols */
if (isdigit(argv[i + 1][j]) && argv[i + 1][j] != '0') {
/* digits except for 0 */
grid[i][j] = argv[i + 1][j] - '0'; /* convert digit to integer */
} else if (argv[i + 1][j] == '.') {
/* dot */
grid[i][j] = 0;
} else {
/* invalid character */
input_error = 1;
break;
}
}
}
}
/* check if some errors are detected */
if (input_error) {
fputs("invalid usage\n", stderr);
return 1;
}
/* print what is read for testing */
for (i = 0; i < 9; i++) {
for(j = 0; j < 9; j++) {
printf(" %d", grid[i][j]);
}
putchar('\n');
}
return 0;
}发布于 2016-03-13 14:57:05
考虑使用文本文件作为输入,并将filename作为命令行参数。
示例:
#include <stdio.h>
#include <ctype.h>
int main(int argc, char* argv[])
{
int lineCnt;
int posCnt;
FILE* inpFile = NULL;
// check argument and file
if( argc < 2 )
{
printf("run program with argument - name of file\n");
return 1;
}
inpFile = fopen(argv[1], "r");
if( inpFile == NULL )
{
printf("file %s cannot be open\n", argv[1]);
return 2;
}
// reading from file
int grid[9][9] = {0};
int chr;
for( lineCnt = 0; lineCnt < 9; lineCnt++)
{
for ( posCnt = 0; posCnt < 9; posCnt++)
{
// read next not sapce character from file
do{
chr = getc(inpFile);
} while( isspace(chr) );
// check character
if( chr == EOF ) // file is finished but array is not filled
{
printf("file %s if incomplete\n", argv[1]);
return 3;
}
if(chr == '.') // if(chr == '.' || chr == '0')
{
grid[lineCnt][posCnt] = 0;
}
else if(chr > '0' && chr <= '9')
{
grid[lineCnt][posCnt] = chr - '0';
}
else
{
printf("file %s has incorrect format\n", argv[1]);
return 4;
}
}
}
// test output of input data
for( lineCnt = 0; lineCnt < 9; lineCnt++)
{
for ( posCnt = 0; posCnt < 9; posCnt++)
{
printf("%i ", grid[lineCnt][posCnt]);
}
printf("\n");
}
}
如果您编译此示例并运行为
./sudoku.c sudoku1.txtsudoku1.txt是这样的
1...5.7..
...3.5.91
.5.6.7.87
11111....
....2222.
6.6.6.6.6
.1.1.1.1.
1.1.1.1.1
.9.9.9.99你就会明白我的想法
https://stackoverflow.com/questions/35967456
复制相似问题