24 / 07 / 11

「一生一芯」Learn C the hard way - Ex 13

练习 13:Switch语句

#include <stdio.h> int main(int argc, char *argv[]) { if(argc != 2) { printf("ERROR: You need one argument.\n"); // this is how you abort a program return 1; } int i = 0; for(i = 0; argv[1][i] != '\0'; i++) { char letter = argv[1][i]; switch(letter) { case 'a': case 'A': printf("%d: 'A'\n", i); break; case 'e': case 'E': printf("%d: 'E'\n", i); break; case 'i': case 'I': printf("%d: 'I'\n", i); break; case 'o': case 'O': printf("%d: 'O'\n", i); break; case 'u': case 'U': printf("%d: 'U'\n", i); break; case 'y': case 'Y': if(i > 2) { // it's only sometimes Y printf("%d: 'Y'\n", i); } break; default: printf("%d: %c is not a vowel\n", i, letter); } } return 0; }

Bug:在前三个字母的 Y 不会被输出。(与附加题 3 相关)

附加题 1

编写另一个程序,在字母上做算术运算将它们转换为小写,并且在switch中移除所有额外的大写字母。

#include <stdio.h> int main(int argc, char *argv[]) { if(argc != 2) { printf("ERROR: You need one argument.\n"); return 1; } int i = 0; for(i = 0; argv[1][i] != '\0'; i++) { char letter = argv[1][i]; if(letter >= 'A' && letter <= 'Z') letter = letter - ('A' - 'a'); printf("%c",letter); } printf("\n"); return 0; }

为什么需要用到 switch 呢……

附加题 2

使用','(逗号)在for循环中初始化letter

int i = 0; char letter; for(i = 0, letter = argv[1][i]; argv[1][i] != '\0'; i++, letter = argv[1][i]) { ... }

附加题 3

使用另一个for循环来让它处理你传入的所有命令行参数。

int i = 0, j = 0; char letter; for(j = 1; j < argc; j++) { printf("\n"); for(i = 0, letter = argv[j][i]; argv[j][i] != '\0'; i++, letter = argv[j][i]) { ... } }
⮞ ./ex13_3 Hello World. YYYYYYY 0: H is not a vowel 1: 'E' 2: l is not a vowel 3: l is not a vowel 4: 'O' 0: W is not a vowel 1: 'O' 2: r is not a vowel 3: l is not a vowel 4: d is not a vowel 5: . is not a vowel 0: Y is not a vowel 1: Y is not a vowel 2: Y is not a vowel 3: 'Y' 4: 'Y' 5: 'Y' 6: 'Y'

附加题 4

将这个switch语句转为if语句,你更喜欢哪个呢?

#include <stdio.h> int main(int argc, char *argv[]) { if(argc != 2) { printf("ERROR: You need one argument.\n"); // this is how you abort a program return 1; } int i = 0; for(i = 0; argv[1][i] != '\0'; i++) { char letter = argv[1][i]; if (letter == 'a' || letter == 'A') { printf("%d: 'A'\n", i); } else if (letter == 'e' || letter == 'E') { printf("%d: 'E'\n", i); } else if (letter == 'i' || letter == 'I') { printf("%d: 'I'\n", i); } else if (letter == 'o' || letter == 'O') { printf("%d: 'O'\n", i); } else if (letter == 'u' || letter == 'U') { printf("%d: 'U'\n", i); } else if (letter == 'y' || letter == 'Y') { if(i > 2) { // it's only sometimes Y printf("%d: 'Y'\n", i); } } else { printf("%d: %c is not a vowel\n", i, letter); } } return 0; }

在“Y”的例子中,我在if代码块外面写了个break。这样会产生什么效果?如果把它移进if代码块,会发生什么?自己试着解答它,并证明你是正确的。

break 在外会导致 y 如果出现在前三个字母则不会被输出,如果移入代码块,才能正确输出位于前三个字母的 y。