C/C++从字符串中提取出数字的方法回顾

在对格式化的数据进行处理的时候,很多时候需要在字符串中进行数据的提取,

如果使用Oracle数据库,可以用里面的非常强大的sqlldr功能进行数据的提取和导入。

在C/C++中,可以自定义个方法提取出数字字符串,再使用atoi, atof之类的方法转换为数字。

C/C++中有sprintf方法可以把一系列数字转换为字符串,也提供了从字符串中提取出数字的方法。

1. fscanf

https://baike.baidu.com/item/fscanf/10942374?fr=aladdin

#include <stdio.h>

#include <stdlib.h>

int main()

{

   char str1[10], str2[10], str3[10];

   int year;

   FILE * fp;

   fp = fopen ("file.txt""w+");

   fputs("We are in 2014", fp);

      rewind(fp);

   fscanf(fp, "%s %s %s %d", str1, str2, str3, &year);

      printf("Read String1 |%s|\n", str1 );

   printf("Read String2 |%s|\n", str2 );

   printf("Read String3 |%s|\n", str3 );

   printf("Read Integer |%d|\n", year );

   fclose(fp);

      return(0);

}

输出结果:

1

2

3

4

Read String1 |We|

Read String2 |are|

Read String3 |in|

Read Integer |2014|

2. istringstream 类

istringstream 提供了类似流的方式去获取数据,如

https://blog.csdn.net/qq_35976351/article/details/84799484

int main() {
    ifstream fin;
    istringstream iss;
    string s;
    double t;
    // 按行读取,每行的结束是回车区分
    fin.open("transform.txt");
    while(getline(fin, s)) {
        iss.clear();
        iss.str(s);
        while(iss>>t) {
            cout<<t<<" ";
        }
        cout<<endl;
    }
————————————————
版权声明:本文为CSDN博主「Erick_Lv」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_35976351/article/details/84799484

但是istringstream的默认分割符是空格,功能有些受限。

getline方法获取字符串的时候可以指定结束符,可以结合起来进行数字的提取

https://www.cnblogs.com/TheKat/p/8065054.html

一个测试程序

#include <fstream>
#include <iostream>
#include <string>
//for istringstream
#include <sstream>

using namespace std;

//
/*  src.txt
time, data
0, 0.1
0.001, 12.2
0.002, 13.1
0.003, 11.1
0.004, 12.2
0.005, 13.3
0.006, 15
*/

int main(int argc, char* argv[])
{
	ifstream instream;
	instream.open("D:\\code\\time2012\\getData\\getData\\Debug\\src.txt");

	//write file
	ofstream out;
	out.open("result.txt");

	if (!instream.is_open())
	{
		cerr << "create file failed!" << endl;
		return -1;
	}

	int num = 0;
	int line = 0;
	string str = "";
	
	//skip the first line
	getline(instream, str);

	istringstream iss;
	
	//str.replace(pos,old_value.length(),new_value); 

	double time=0;
	double value;

	double left = -1;//a min value as beginning
	bool decline = false;

	string tmp;

	while (getline(instream, str) && line <= 6)
	{
		cout << str << endl;
		line++;

		iss.clear();
		iss.str(str);
		iss >> time;
		iss >> tmp;
		iss >> value;


		//get a bottom
		if (decline && left < value)
		{
			cout << "get bottom " << left << endl;
			//write
			out << left << endl;

			num++;
			decline = false;
		}

		if (left >= value)
		{
			decline = true;
		}
		
		left = value;

		cout << "get value=" << time << tmp << value << endl;

		
	}

	instream.close();

	out.close();

	return 0;
}
发布了336 篇原创文章 · 获赞 13 · 访问量 33万+

猜你喜欢

转载自blog.csdn.net/aaajj/article/details/103949314
今日推荐