c/c++ 读入一行不确定个数的整数
时间:2014-05-13 20:52:45
收藏:0
阅读:479
假设有一个文件,文件的每一行包括n个整数,整数之间以一个空格隔开,文件总共有m行,但是事先不知道n,m。如何每次从文件中读取一行整数放到一个数组中。
可以分为两步:1、首先从文件中读入一行字符串,2、然后从这一行字符串中解析出整数。
对于第一步,我们可以有c、c++两种风格的做法
c风格:
1
2
3
4
5
6 |
FILE
*fp = fopen ( "input.txt" , "r" ); char
buf[10000]; while ( fgets (buf, 10000, fp)) { //从buf解析出整数 } |
c++风格:
1 |
ifstream infile( "input.txt" ); |
1
2
3
4
5 |
string s; while (getline(infile, s)) { //从s中解析出整数 } |
经过测试如果不考虑解析整数的时间,这两种方法耗时相差不大,说明getline和fgets效率基本相同。
对于第二步,从一行字符串中解析出整数,以下提供3中方法, 为了简单,我们只是返回从字符串中解析出的整数个数,并没有把他们存入数组
方法1:利用字符串流istringstream
1
2
3
4
5
6
7
8 |
int getInt(string &s) { istringstream iss(s); int
num, res = 0; while (iss >> num) res++; return
res; } |
方法2:利用strstr函数和atoi函数
1
2
3
4
5
6
7
8
9
10
11
12
13
14 |
int getInt( const
char *buf) { const
char *loc = buf; int
res = 0; atoi (buf); loc = strstr (buf, " " ); while (loc != NULL) { atoi (loc+1); res++; loc = strstr (loc+1, " " ); } return
res; } |
方法3:利用strtok函数(该函数用法可参考关于函数strtok和strtok_r的使用要点和实现原理(一))和atoi函数
1
2
3
4
5
6
7
8
9
10
11
12 |
int getInt( char
*buf) { char
*p = strtok (buf, " " ); int
res = 0; while (p) { atoi (p); res++; p = strtok (NULL, " " ); } return
res; } |
这三种方法的耗时,方法2和方法2基本相同(方法3的时间略多),方法1差不多是方法2的10倍
【版权声明】转载请注明出处:
评论(0)