求字符串中的空格數

                 在CSDN博客中看到了一篇求字符串中的空格數的文章,想想這個是一個不錯的問題了,博客中的代碼爲:

Code:
  1.  1. #include <iostream>   
  2.  2. #include <stdlib.h>   
  3.  3. #include <stdio.h>    
  4.  4.  
  5.  5. using namespace std;  
  6.  6.  
  7.  7. int main(int argc, char *argv[])  
  8.  8. {  
  9.  9.     int count = 0 ;  
  10. 10.     char* str  ;  
  11. 11.     printf("Input a string:");   
  12. 12.  
  13. 13.     gets(str);     //此處不能使用scanf(%s,str)或者cin>>str; 因爲這兩者個函數在執行過程中發現字符串中還有空格  
  14. 14.                          //或者回車符就會結束運行。故無法通過這兩個函數計算字符串中的字符數  
  15. 15.       
  16. 16.     char* p = str ;  
  17. 17.     while(*p!='/0')  
  18. 18.     {  
  19. 19.         if(*p==' ') count++ ;  
  20. 20.         p++ ;      
  21. 21.     }  
  22. 22.       
  23. 23.     cout<<"Your input string is :"<<str<<endl ;  
  24. 24.     cout<<"The Count of space= "<<count<<endl ;  
  25. 25.     
  26. 26.   system("PAUSE");    
  27. 27.   return 0;  
  28. 28. }  

看完代碼後,我發現一個問題,gets的參數指針,作者並沒有爲其申請空間,可謂一大失誤。但作者代碼中的註釋說的很好,對於一個字符串,當我們使用char * str = new char[BUFFER_LEN];scanf("%s",str);或者cin >> str;接收它時,遇到空格就會結束接收。即使我們使用string str;  cin >> str;也是如此.因此作者在接收字符串是選擇了gets().這好像也能滿足作者的需求。但我們看看gets()的描述後,可以找到一個更好的辦法.

Get string from stdin  

Reads characters from stdin and stores them as a string into str until a newline character ('/n') or the End-of-File is reached.  

The ending newline character ('/n'is not included in the string.  

null character ('/0'is automatically appended after the last character copied to str to signal the end of the C string.  

Notice that gets does not behave exactly as fgets does with stdin as argument: First, the ending newline character is not included with 

gets while with fgets it is. And second, gets does not let you specify a limit on how many characters are to be read, so you must be careful 

with the size of the array pointed by str to avoid buffer overflows. 

看完這段文字,我們可以使用fgets函數來完成我們讀入字符串的工作:

Code:
  1. #include <iostream>  
  2. #include <stdio.h>  
  3. #define BUFFER_LEN 1024  
  4. using namespace std;  
  5. int main(int argc, char *argv[])  
  6. {  
  7.    char str[BUFFER_LEN];  
  8.   fgets(str,BUFFER_LEN,stdin);  
  9.   cout << str << endl;  
  10.   return 0;  
  11. }  

我相信這樣更好些,至少它增加了一個額外的長度參數,防止了內存溢出問題的出現。這裏有一個需要注意的問題就是fgets()和gets()都有一個重要的功能:

A null character is automatically appended in str after the characters read to signal the end of the C string.

這個功能很是重要,否則就不能使用:

Code:
  1. char* p = str ;  
  2. while(*p!='/0')  
  3. {  
  4.    if(*p==' ') count++ ;  
  5.    p++ ;      
  6. }

這種方式來計算空格數了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章