将来自arg in c的输入值添加到数组解析器的数组中

时间:2016-03-13 06:52:36

标签: c sudoku

我是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}};

有什么建议吗?

非常感谢任何帮助

2 个答案:

答案 0 :(得分:1)

只需阅读简单的循环。

(condition) ? statement : statement

答案 1 :(得分:0)

考虑使用文本文件作为输入,并将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.txt

sudoku1.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

你会理解我的想法