stream - Reading txt file in C++ to strings and floats -
i need read *.txt file. contains words , numbers, , looks this:
firstword:12,13.0secondword18.7thirdword2,3,89
i need extract words strings, , numbers floats. main problem cannot solve there no delimiters before "words" (otherwise i'd use getline).
thank you!
note: words not contain numbers, example, word 'num1' impossible.
with sstream
, more requires delimiter, there none in file.
by using functions found in standard c library, can character character without delimiter. , not elegant.
this 1 way of extracting words , doubles text file text.txt
contaning firstword:12,13.0secondword18.7thirdword2,3,89
.
this solution uses funtion isalpha()
extract alphabet related , stores in array extractedwords[]
.
for doubles, uses isdigit()
, atof()
extract number related , stores in array extracteddoubles[]
.
#include<string> #include<fstream> #include<iostream> #include <stdlib.h> using namespace std; char mainbuffer[1024]={' '}; size_t fsize ; string extractedwords[100]; double extracteddoubles[100]={0}; string buf2str(const char* buffer); void loadfiletobuffer(char *filename); void extractwords(); void extractfloats(); int main(){ loadfiletobuffer("text.txt" ); extractwords(); extractfloats(); cout<<"\n"; return 0; } string buf2str(const char* buffer){ return string(buffer); } void loadfiletobuffer(char *filename){ ifstream infile; infile.open(filename); infile.read(mainbuffer, sizeof mainbuffer); if (infile.eof()){ fsize = infile.gcount(); cout<<"fsize = "<<fsize<<" , data = " << mainbuffer <<" \n "; } else if (infile.fail()){ // other error... } else{ // buf must full, file larger... } infile.close(); } void extractwords(){ char character; int i=0; int j=0; char shortbuffer[16]={' '}; int seek=0; cout<<"\n"; seek=0; i=0; j=0; while ( seek<=fsize ) { character=mainbuffer[seek]; if ( isalpha(character) ) { shortbuffer[i]=character; i++; } else{ shortbuffer[i]='\0'; if (strlen(shortbuffer)>2){ extractedwords[j]=buf2str(shortbuffer); i=0; j++; } } seek++; } for(int ii=0;ii<j;ii++) cout<<extractedwords[ii] <<"\n"; cout<<"\n"; } void extractfloats(){ char character; int i=0; int j=0; char shortbuffer[16]={' '}; double dvalue=0; int seek=0; cout<<"\n"; seek=0; i=0; j=0; while ( seek<=fsize ) { character=mainbuffer[seek]; if ( isdigit(character) || character=='.' ){ shortbuffer[i]=character; i++; } else{ shortbuffer[i]='\0'; dvalue=atof(shortbuffer); if (dvalue != 0) { extracteddoubles[j]=dvalue; j++; i=0; } } seek++; } for(int ii=0;ii<j;ii++) cout <<extracteddoubles[ii]<<"\n"; cout<<"\n"; }
Comments
Post a Comment