论坛首页 编程语言技术论坛

利用STL判断string是否为整数

浏览 9617 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (5)
作者 正文
   发表时间:2011-10-15  
C++

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

 

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开始。

 

 

   发表时间:2011-10-17  
何不试试boost的库?
0 请登录后投票
   发表时间:2011-10-18  
mathgl 写道
何不试试boost的库?

boost还没有学,正在学习中
0 请登录后投票
   发表时间:2011-10-19  
一坨坨破代码。

这种这么简单的事情,整数无非就是每个字符的ascii码都落在48到57(或者58?)之间的字符串。
0 请登录后投票
   发表时间:2011-10-27  
ascii
48-57之间的 就是 数字了
0 请登录后投票
   发表时间:2011-10-27  
其实这段程序中,有一个bug
0 请登录后投票
   发表时间:2011-10-27  
直接用cctype.h里面的函数不就得了嘛。。
0 请登录后投票
   发表时间:2011-10-27  
int ismun(string strinfo)  看到这个我就知道LZ没写过多少CPP
0 请登录后投票
   发表时间:2011-10-28  
StringUtil中有个判断方法
0 请登录后投票
   发表时间:2011-10-28  
sniffer123 写道
int ismun(string strinfo)  看到这个我就知道LZ没写过多少CPP

高见,确实还没写过多少,正在学习
0 请登录后投票
论坛首页 编程语言技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics