输入一个字符串,串内有数字和非数字字符。例如:abc456 sd78fd123s 789df,将其中连续的数字作为一个整数,依次存放到另一个整型数组b中。例如上述例子,将456放入b[0]中,78放入b[1]中……,统计出整数的个数并输出这些整数。要求在主函数中完成输入和输出工作,设计一个函数,把指向字符串的指针和指向整数数组的指针作为函数的参数,完成从字符串中提取整数的工作,并将整数的个数作为函数值返回。
一种解法:
#include<iostream>
#include<sstream>
#include<iterator>
#include<vector>
#include<algorithm>
using namespace std;
bool f(int c){return !isdigit(c);}
size_t extract(string s, vector<int> &v){
replace_if(s.begin(), s.end(), f, ' ');
istringstream iss(s, istringstream::in);
int num;
while (iss >> num) v.push_back(num);
return v.size();
}
int main()
{
string s;
getline(cin, s);
vector<int> v;
extract(s, v);
copy(v.begin(), v.end(), ostream_iterator<int>(cout, "/n"));
#include<sstream>
#include<iterator>
#include<vector>
#include<algorithm>
using namespace std;
bool f(int c){return !isdigit(c);}
size_t extract(string s, vector<int> &v){
replace_if(s.begin(), s.end(), f, ' ');
istringstream iss(s, istringstream::in);
int num;
while (iss >> num) v.push_back(num);
return v.size();
}
int main()
{
string s;
getline(cin, s);
vector<int> v;
extract(s, v);
copy(v.begin(), v.end(), ostream_iterator<int>(cout, "/n"));
return 0;
}
}
第二种:
#include <stdio.h>
#include <string.h>
#include<iostream>
#include<cctype>
using namespace std;
char str[100]; //字符数组
int integer[100];//要存放的整数数组
int getInt(char *,int *);
void main()
{
int count;
cin.getline(str,100);
count = getInt(str,integer);
for(int i = 0; i < count; i++)
{
cout<<integer[i]<<endl;
}
}
int getInt(char *str, int *intger)
{
char Int[20];
int temVal = 0;
int count = 0;
int flag = 1;
int start = 0;
int end = 0;
int len = strlen(str);
for(int i = 0 ; i < len; i++)
{
if(isdigit(str[i]))
{
if(flag)
{
start = i;
flag = 0;
}
if( !isdigit(str[i+1]) )
{
end = i;
flag = 1;
strncpy(Int,str+start,end-start+1);
Int[end-start+1] = 0;
temVal = atoi(Int);
integer[count++] = temVal;
}
}
}
return count;
}
#include <string.h>
#include<iostream>
#include<cctype>
using namespace std;
char str[100]; //字符数组
int integer[100];//要存放的整数数组
int getInt(char *,int *);
void main()
{
int count;
cin.getline(str,100);
count = getInt(str,integer);
for(int i = 0; i < count; i++)
{
cout<<integer[i]<<endl;
}
}
int getInt(char *str, int *intger)
{
char Int[20];
int temVal = 0;
int count = 0;
int flag = 1;
int start = 0;
int end = 0;
int len = strlen(str);
for(int i = 0 ; i < len; i++)
{
if(isdigit(str[i]))
{
if(flag)
{
start = i;
flag = 0;
}
if( !isdigit(str[i+1]) )
{
end = i;
flag = 1;
strncpy(Int,str+start,end-start+1);
Int[end-start+1] = 0;
temVal = atoi(Int);
integer[count++] = temVal;
}
}
}
return count;
}