利用STL判断string是否为整数

本文介绍了如何通过编程技巧从文件中高效地筛选出整数,包括按行读取、验证整数属性并存储到向量的过程,提供了一个完整的代码示例,帮助开发者快速实现数据提取。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

有这么一个文件,内容如下:

 

1
2
111
222
111
111111
22344
oaini
woain
sdjjj
woaini

 

 怎么将其中的整数区分出来?

 

解决思路:

 

1、按行输入;

2、定义为string;

3、判断该string是否为整数;

4、存入vector;

5、输出。

 

整个过程,第三步是核心。

 

 

完整代码如下:

 

 

#include <string>
#include <iostream>
#include<fstream>
#include<algorithm>
#include<vector>
using namespace std;
int ismun(string strinfo)
{
	string strset="1234567890";
	int first = strinfo.find_first_of(strset);
	if(first == string::npos) 
	{
		return -1;
	}  
	return 0;
}
int main(){
	ifstream in("proc.txt");
	string strtemp;
	vector<string> myvector;
	while(getline(in,strtemp,'\n'))
	{
		if(ismun(strtemp) == 0)		
		{
			myvector.push_back(strtemp);
		}
	}
	vector<string>::iterator it;
	for(it = myvector.begin();it != myvector.end();it ++)
	{
		cout<<*it<<endl;
	}
	return 0;
}

 

 函数介绍:

find_first_of()函数介绍:

 

 

find_first_of 

语法: size_type find_first_of( const basic_string &str, size_type index = 0 ); 

size_type find_first_of( const char *str, size_type index = 0 ); 

size_type find_first_of( const char *str, size_type index, size_type num ); 

size_type find_first_of( char ch, size_type index = 0 ); 

 

 

find_first_of()函数: 

 

查找在字符串中第一个与str中的某个字符匹配的字符,返回它的位置。搜索从index开始,如果没找到就返回string::npos 

查找在字符串中第一个与str中的某个字符匹配的字符,返回它的位置。搜索从index开始,最多搜索num个字符。如果没找到就返回string::npos, 

查找在字符串中第一个与ch匹配的字符,返回它的位置。搜索从index开始。

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值