C中的字符串识别问题

liuzq133 2007-02-10 01:08:23
现在要编写一个程序,统计输入的一行字符中字母、数字以及空格的个数,我使用字符串数组来接受输入,可是这个字符串数组一遇到空格字符就认为输入结束了,但是该空格字符后面仍然有字符输入,请问怎样解决这个问题
...全文
367 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
xyjchinese 2007-02-12
  • 打赏
  • 举报
回复
用gets()
或者
char chStringByScanf[20];
scanf("%[^/n]",chStringByScanf);
printf("String: %s/n",chStringByScanf);
Silent_Spring 2007-02-11
  • 打赏
  • 举报
回复
lex
LuGuangbO 2007-02-11
  • 打赏
  • 举报
回复
那我就不知道了
我没学C++
在学C
呵呵 你问问其他人吧
liuzq133 2007-02-11
  • 打赏
  • 举报
回复
上面的使用C中的标准输入输出函数做的,但是换成了C++的cin好像就不行了,也就是说scanf("%c",&c);不能换成cin >> c,不知道为什么
LuGuangbO 2007-02-10
  • 打赏
  • 举报
回复
#include <stdio.h>
#include <ctype.h>
int main(void)
{
char ch;
int ct_alpha=0,ct_space=0,ct_digit=0 ;
printf("Enter string:\n") ;
while(scanf("%c",&ch),ch!='\n')
{ if(isalpha(ch)) ct_alpha++ ; /*统计字母*/
if(isdigit(ch)) ct_digit++ ; /*统计数字*/
if(ch==' ') ct_space++ ; /*统计空格*/
}
printf("Letter=%d,Digit=%d,Space=%d\n",ct_alpha,ct_digit,at_space) ;
return 0;
}
Immortality_HeeRo 2007-02-10
  • 打赏
  • 举报
回复
可以用gets()
takecareofmyself 2007-02-10
  • 打赏
  • 举报
回复
由于scanf("%s")遇到空格、制表、回车就会结束,因此,改一下就行了

int main()
{
char c;
int alphaCount = 0, spaceCount = 0, numberCount = 0;
printf("Input a string:\n");
while( 1 )
{
scanf("%c",&c);
if( c == '\n' )
break;
if( ( c >= 'a' && c <= 'z' ) || ( c >= 'A' && c <= 'Z') )
alphaCount++;
if( c >= '0' && c <= '9' )
numberCount++;
if( c == ' ' )
spaceCount++;
}
printf("\n");
printf("alpha:%d space:%d number:%d",alphaCount,spaceCount,numberCount);
return 0;
}
飞驰的青蛙 2007-02-10
  • 打赏
  • 举报
回复
cin.get(str,256);

33,311

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 新手乐园
社区管理员
  • 新手乐园社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧