在CSDN博客中看到了一篇求字符串中的空格數的文章,想想這個是一個不錯的問題了,博客中的代碼爲:
- 1. #include <iostream>
- 2. #include <stdlib.h>
- 3. #include <stdio.h>
- 4.
- 5. using namespace std;
- 6.
- 7. int main(int argc, char *argv[])
- 8. {
- 9. int count = 0 ;
- 10. char* str ;
- 11. printf("Input a string:");
- 12.
- 13. gets(str); //此處不能使用scanf(%s,str)或者cin>>str; 因爲這兩者個函數在執行過程中發現字符串中還有空格
- 14. //或者回車符就會結束運行。故無法通過這兩個函數計算字符串中的字符數
- 15.
- 16. char* p = str ;
- 17. while(*p!='/0')
- 18. {
- 19. if(*p==' ') count++ ;
- 20. p++ ;
- 21. }
- 22.
- 23. cout<<"Your input string is :"<<str<<endl ;
- 24. cout<<"The Count of space= "<<count<<endl ;
- 25.
- 26. system("PAUSE");
- 27. return 0;
- 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.
A 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函數來完成我們讀入字符串的工作:
- #include <iostream>
- #include <stdio.h>
- #define BUFFER_LEN 1024
- using namespace std;
- int main(int argc, char *argv[])
- {
- char str[BUFFER_LEN];
- fgets(str,BUFFER_LEN,stdin);
- cout << str << endl;
- return 0;
- }
我相信這樣更好些,至少它增加了一個額外的長度參數,防止了內存溢出問題的出現。這裏有一個需要注意的問題就是fgets()和gets()都有一個重要的功能:
A null character is automatically appended in str after the characters read to signal the end of the C string.
這個功能很是重要,否則就不能使用:
- char* p = str ;
- while(*p!='/0')
- {
- if(*p==' ') count++ ;
- p++ ;
- }
這種方式來計算空格數了。