2025年3月20日 星期四 甲辰(龙)年 月十九 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > C语言

C语言输入一行数据并统计其长度

时间:12-29来源:作者:点击数:79

从控制台输入一行数据并计算它的长度;输入空行结束程序

  • #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]: 城东书院
len = 11, line = 城东书院
Enter a string [CR to exit]: http://www.cdsy.xyz/
len = 29, line = http://www.cdsy.xyz/
Enter a string [CR to exit]:
Press any key to continue
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门