C语言输入一行数据并统计其长度
从控制台输入一行数据并计算它的长度;输入空行结束程序
Enter a string [CR to exit]: 123456
len = 6, line = 123456
Enter a string [CR to exit]: C语言中文网
len = 11, line = C语言中文网
Enter a string [CR to exit]: http://see.xidian.edu.cn/cpp/
len = 29, line = http://see.xidian.edu.cn/cpp/
Enter a string [CR to exit]:
Press any key to continue
#include <stdio.h> #define MAXBUF 128 int getline(char line[], int nmax); int main(void){ int len; char buffer[MAXBUF]; while(1){ len = getline(buffer, MAXBUF); if (len==0) break; printf("len = %d, line = %s\n", len, buffer); }; } // 提示用户输入一行字符串,最大长度为 nmax,并返回字符串的长度 int getline(char line[], int nmax) { int len; char c; len = 0; printf("Enter a string [CR to exit]: "); while(((c=getchar())!='\n') && len<nmax-1) line[len++]=c; line[len]='\0'; return len; }可能的输出结果:
Enter a string [CR to exit]: 123456
len = 6, line = 123456
Enter a string [CR to exit]: C语言中文网
len = 11, line = C语言中文网
Enter a string [CR to exit]: http://see.xidian.edu.cn/cpp/
len = 29, line = http://see.xidian.edu.cn/cpp/
Enter a string [CR to exit]:
Press any key to continue