在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++ ;
- }
这种方式来计算空格数了。