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