pat1009,字符串的输入处理

地址:http://pat.zju.edu.cn/contests/pat-b-practise/1009


本题中遇到的问题:

scanf("%s%c", buf, c);

忘记&,运行时:XX已停止工作。调试错误:非法访问



修改后,scanf("%s%c", buf, &c);运行正确:

#include

int main(){

#ifdef ONLINE_JUDGE
#else
	freopen("E:\\in.txt", "r", stdin);
#endif


	char sen[80][100];
	int cn=0;
	char c;


	while(scanf("%s%c", sen[cn++], &c) != EOF){
		if(c == '\n'){
			printf("%s\n", sen[--cn]);
			continue;
		}
		
		while(scanf("%s%c", sen[cn++], &c) != EOF){
			if (c == '\n')
				break;
		}
		while(--cn >0){
			printf("%s ", sen[cn]);
		}
		printf("%s\n", sen[cn]);

	}
	return 0;
}








另外一种方法,1个字符一个字符读入处理。掌握这种方法是非常有必要的。

需要注意的事项:

字符串读入结束后需要加结束标记'\0',如果忘记,调试时,可以看到:


当然程序运行时也会错误:输出时直接出现乱码,因为没有添加字符串的借宿标识符


AC代码:

#include
#include

int main(){

#ifdef ONLINE_JUDGE
#else
	freopen("E:\\in.txt", "r", stdin);
	freopen("E:\\out.txt", "w", stdout);
#endif


	char sen[80][100], buf[100];
	int cn=0;
	char c;
	
	while(scanf("%c", &c) != EOF){
		if(c == '\n'){
			continue;
		}// skip blank

		//first char  not new line 
		int len=0;
		buf[len++]=c;
		while(scanf("%c", &c) != EOF){
			if(c == '\n'){
				buf[len]='\0';
				strcpy(sen[cn++], buf);//end of a word, save
				len=0;
				break; // end of a line
			}
			if(c == ' '){
				buf[len]='\0';//add \0
				strcpy(sen[cn++], buf);//end of a word, save
				len=0;
				continue;// next word
			}
			buf[len++]=c;
		}//end of reading a line

		while(--cn >0){
			printf("%s ", sen[cn]);
		}
		printf("%s\n", sen[cn]);
		cn=0;
	}

	
	return 0;
}


你可能感兴趣的:(pat1009,字符串的输入处理)