6-24 D字符串的输入 (5分)


6-24 D字符串的输入 (5分)
 

D字符串是动态分配内存的字符串,它也采用char数组来保存字符串中的字符,但是这个数组是在堆中动态分配得到的。

本题要求编写D字符串的读入一个单词的函数。

函数接口定义:

char *dstr_readword(); 
 

dstr_readword从标准输入读入一个字符串,到回车换行、空格或Tab字符、或遇到输入结束为止。返回读入的字符串。

注意这里可能读到的字符串长度没有限制。

裁判测试程序样例:

#include <stdio.h> #include <stdlib.h> #include <string.h> char *dstr_readword(); int main() { char *s = dstr_readword(); printf("%lu-%s\n", strlen(s), s); } /* 请在这里填写答案 */ 
 

输入样例:

123A
 

输出样例:

4-123A




char *dstr_readword()
{
 int maxsize=1000;
 char *s=malloc(maxsize*sizeof(char));
 int count=0;
 char temp;
 while(scanf("%c",&temp)!=EOF&&temp!='\n'&&temp!='\t'&&temp!=' ')
 {
  s[count++]=temp;
  if(count==maxsize)
  {
   maxsize=2*maxsize;
   s=realloc(s,maxsize*sizeof(char));
  }
 }
 return s;
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM