1. 程式人生 > >C-輸入句子,逆語序輸出

C-輸入句子,逆語序輸出

/*輸入一個句子,將其反序輸出
*/記憶體訪問出錯

#include<stdio.h>

int main(void) {
	char code[50];
	int i, j, k1, k2;
	char c;
	i = j = k1 = k2 = 0;
for (i = 0; i < 50; i++) {
	code[i] = ' ';
}
i = 0;

printf("Enter a sentence: ");

while (i < 50 && (c = getchar()) != '\n') {	//輸入終止條件——回車
	code[i] = c;
	i++;
}

printf("Reveral of sentence: ");

for (i = 49; i > 0; i++) {
	if (code[i] != ' '&&code[i - 1] == ' ') {	//單詞頭用k2標記
		k2 = i;
	}
	if (code[i] == ' '&&code[i - 1] != ' ') {	//單詞尾用k1標記
		k1 = i;
	}

	if (k2 < k1) {
		for (j = k2; j <= k1; j++) {
			printf("%c",code[j]);
		}
		printf(" ");
	}
}

for (j = 0; j <= k1; j++) {		// 輸出最前面一個單詞
	printf("%c", code[j]);
}

return 0;

}