When formatting of data processing, data often need to be extracted in the string,
If you are using an Oracle database, you can extract and import data with very powerful features sqlldr inside.
In C / C ++, it is possible to customize a method of extracting the digital strings, then use atoi, atof method or the like into digital.
C / C ++ methods can have a series of numbers sprintf converted to a string, also it provides a method to extract numbers from a string.
1. fscanf
https://baike.baidu.com/item/fscanf/10942374?fr=aladdin
|
Output:
1 2 3 4 |
|
2. istringstream class
istringstream provides a similar manner to obtain the data stream, such as
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;
}