在C中使用不同的库
我只是从头开始编写一个程序,它可以计算用户输入的大写和小写字母以及空格。 从那时起,我发现那些特定function的代码已经在另一个库中预先编写了! 我的问题是,我在下面编写的所有代码如何通过使用来简化
isupper(int c)
, islower(int c)
和isspace(int c)
,它们在ctype.h
中定义。
#include int main(void){ int iochar, numdigits=0, numlower=0, numupper=0, numwhites=0; printf("Please enter a phrase:\n\n"); while((iochar=getchar())!=EOF) { if ((iochar==' ')||(iochar=='\t')||(iochar=='\n')) { numwhites++; putchar(iochar); } else if((iochar>='0')&&(iochar<='9')) { numdigits++; putchar(iochar); } else if(('a'<=iochar)&&(iochar<='z')) { numlower++; putchar(iochar-32); } else if(('A'<=iochar)&&(iochar<='Z')) { numupper++; putchar(iochar); } else putchar(iochar); } printf("%d white characters, %d digits, ",numwhites,numdigits); printf("%d lowercase have been converted to ",numlower); printf("uppercase and %d uppercase.\n",numupper); printf("\n\n"); return 0;}
这里写的更好,清理得更好:
#include #include int main(int argc, char **argv) { int iochar, numdigits=0, numlower=0, numupper=0, numwhites=0; printf("Please enter a phrase:\n\n"); while ((iochar=getchar()) != EOF) { // increase counts where necessary if (isspace(iochar)) { numwhites++; } else if (isdigit(iochar)) { numdigits++; } else if (islower(iochar)) { numlower++; iochar = toupper(iochar); } else if (isupper(iochar)) { numupper++; } // this happens always, don't put it in the if's putchar(iochar); } printf("%d white characters, %d digits, ", numwhites, numdigits); printf("%d lowercase have been converted to ", numlower); printf("uppercase and %d uppercase.\n", numupper); printf("\n\n"); return 0; }
只需#include
然后改变例如
if((iochar==' ')||(iochar=='\t')||(iochar=='\n'))
至
if (isspace(iochar))
等等
有关详细信息,请参阅man ctype 。