file - Read comma separated values with stray whitespaces from a textfile in c++ -
i have file contains string,int,int values in multiple lines.
delhi,12,13 mumbai,100 , 101 kolkata,11, 12
the values separated commas there can stray whitespaces in between.my current code :
#include<cstdio> #include<iostream> #include<string> using namespace std; int main() { file *f = fopen("input.txt","r"); int lines = 0; char c = getc(f); while(c != eof) { if(c == '\n') { lines++; } c = getc(f); } lines++; string arr[lines]; int t1[lines]; int t2[lines]; char s1[100],s2[100],s3[100]; int x,y; fclose(f); f = fopen("input.txt","r"); while (fscanf(f,"%99[^,],%99[^,],%99[^,]", s1, s1, s2)==3) { cout << s1 << s2 << s3 << endl; } }
this doesn't seem quite read values , display on screen first of all. how read string , integer values here(which may have stray whitespaces) , store them array (three arrays precise) ?
try doing this:
fscanf(f,"%[^, ]%*[ ,]%d%*[ ,]%d ", s1, &x, &y);
%[^, ]
=> searches except ,
, <space>
, stores in s1
%*[ ,]
=> searches ,
, <space>
not store anywhere (the *
ensures that)
%d
=> stores number
Comments
Post a Comment