首页 > 代码库 > UVa 232 字符串处理、

UVa 232 字符串处理、

背景:做了三个半小时,代码能力堪忧啊,各种调试,各种出错,要分析一下,这些错点尽量不能再错。

学习:1.对于字符串数组,要把每一行都开大一位,该位用来存放‘\0‘,否则将会出现未知输出。也就是说:字符串二维数组的每一行都可以看做一个字符数组,结尾都有一个‘\0‘.printf在用‘%s‘格式符输出字符串,总是从给定的首地址开始,遇到‘\0‘结束。

2.写程序的时候要有动态的眼光来看待当前写下的代码运行时的样子。运行出错不要理解单步调试,因先猜测是哪里错了,先看代码在脑中模拟。

#include<stdio.h>
#include<string.h>
int main(void)
{
	int n, m, count = 1;
	while (scanf("%d", &n) == 1 && n){
		scanf("%d",&m);
		char puzzle[n][m];
		for (int i = 0; i<n; i++) scanf("%s", puzzle[i]);
		int num[n][m];
		memset(num, 0, sizeof(num));
		int count1 = 1;
		for (int i = 0; i<n; i++)
		for (int j = 0; j<m; j++){
			if ((i - 1<0 || j - 1<0 || puzzle[i - 1][j] == '*' || puzzle[i][j - 1] == '*')&&puzzle[i][j]!='*') {
				num[i][j] = count1++;
			}
			else{
				num[i][j] = 0;
			}
		}
		if (count - 1) printf("\n");
		printf("puzzle #%d:\n", count++);

        //Across deal. 
		printf("Across\n");
		for (int i = 0; i < n; i++)
		for (int j = 0, key = 1; j < m; j++){
			if (num[i][j]){
				while (1){
					if (j + key < m&&puzzle[i][j + key] != '*') key++;
					else break;
				}
				printf("%3d.", num[i][j]);
				for (int ii=j; j < ii + key; j++) printf("%c", puzzle[i][j]);
				printf("\n");
			} 
                        key=1;
		}
		
		//Down deal.
		char ans[count1][n+1];
		memset(ans,'\0',sizeof(ans));
		printf("Down\n");
		for (int i = 0; i < m; i++)
		for (int j = 0, key = 1; j < n; j++){
			if (num[j][i]){
				while (1){
					if (j + key < n&&puzzle[j+key][i] != '*') key++;
					else break;
				}
				/*printf("%2d.", num[j][i]);
				for (int ii=j; j < ii + key; j++) printf("%c", puzzle[j][i]);
				printf("\n");*/
				for (int ii=j,kk=0,gg=num[j][i]; j < ii + key; j++,kk++) {
				ans[gg][kk]=puzzle[j][i];
		    	}
			}
                        key=1;
		}
		for(int jj=1;jj<count1;jj++){
			if(ans[jj][0]!='\0'){
			   printf("%3d.", jj);
			   printf("%s\n",ans[jj]);
			}
		}
	}
	return 0;
}


UVa 232 字符串处理、