字符串中求数字个数

pbfordream 2012-09-10 09:04:58
题目要求

对于给定的一个字符串,统计其中数字字符出现的次数。

输入数据有多行,第一行是一个整数a,表示测试实例的个数,后面跟着a行,每行包括一个由字母和数字组成的字符串。

对于每个测试实例,输出该串中数值的个数,每个输出占一行


以下是我的代码,输出以后是每行字符串中的字符总个数,而不是每行字符串中数字的个数,这是为什么,急求,谢谢!

#include<iostream>
#include<string>
#include<vector>
#include<cctype>
using namespace std;
int main()
{
vector<string> str;
string s;
int a;
cin>>a;
for(int i=0;i<a;++i)
{
cin>>s;
str.push_back(s);
}
string::size_type jx;
for(vector<string>::size_type ix = 0; ix != str.size(); ++ix)
{
for(jx=0;jx!=str[ix].size();++jx)
{
if(isdigit(str[ix][jx]))
++jx;
}
cout<<jx<<endl;
}
return 0;
}
比如输入
4
dasd23
asdasd342sad
sd45sad3
输出
6
12
4
而不是我想要的
2
3
3

...全文
244 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
随风而飞_1 2012-09-10
  • 打赏
  • 举报
回复
计数器和循环控制变量重复使用了
string::size_type jx;
for(vector<string>::size_type ix = 0; ix != str.size(); ++ix)
{
string::size_type num=0;
for(jx=0;jx!=str[ix].size();++jx)
{
if(isdigit(str[ix][jx]))
++num;
}
cout<<num<<endl;
}
return 0;
hongwenjun 2012-09-10
  • 打赏
  • 举报
回复
#include<iostream>
#include<string>
#include<vector>
#include<cctype>
using namespace std;
int main()
{
vector<string> str;
string s;
int a;
cin >> a;
for (int i = 0; i < a; ++i) {
cin >> s;
str.push_back(s);
}
size_t cnt = 0 ;
for (size_t ix = 0; ix != str.size(); ++ix) {
for (size_t jx = 0; jx != str[ix].size(); ++jx) {
if (isdigit(str[ix][jx]))
++cnt;
}
cout << cnt << endl;
cnt = 0;
}
return 0;
}



楼主 计数器 和循环控制叠用了
zjs100901 2012-09-10
  • 打赏
  • 举报
回复
你把jx的当作索引,又把它当作计数器,所以错了。在我这死循环呢,没输出第3行的4。
再定义一个变量吧。
#include<iostream>
#include<string>
#include<vector>
#include<cctype>
using namespace std;
int main()
{
vector<string> str;
string s;
int a;
cin>>a;
for(int i=0;i<a;++i)
{
cin>>s;
str.push_back(s);
}

string::size_type jx;
for(vector<string>::size_type ix = 0; ix != str.size(); ++ix)
{
string::size_type count = 0;
for(jx=0;jx!=str[ix].size();++jx)
{
if(isdigit(str[ix][jx]))
++count;
}
cout<<count<<endl;
}
return 0;
}

64,654

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

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