dimanche 28 janvier 2018

C++ reading files into vectors

I am trying to read values from a file to C++ vectors. The file looks like this:

file f1.txt:
1.,2.
3.,4.
5.,6.
7.,8.
9.,10.

I have code in python 3 to read the file and store values in lists.

def main():
    vec1=[]
    vec2=[]
    with open('f1.txt','r') as f1:
        for line1 in f1:
            a=(line1.strip()).split(sep=',')
            vec1.append(float(a[0]))
            vec2.append(float(a[1]))
    print('First vercor : {0} \nSecond vector: {1}'.format(vec1,vec2))    

#

if __name__=='__main__':
    main()

Output:

First vercor : [1.0, 3.0, 5.0, 7.0, 9.0] 
Second vector: [2.0, 4.0, 6.0, 8.0, 10.0]

I want either to import vec1,vec2 in C++ or create C++ code to achieve the same. The importing option is complicated. I took a look at few C++ examples, but couldn't get as effective (short and simple) way as python code has. Can someone suggest a way to achieve this in C++ - especially splitting the string and putting first part into one vector and second part into the other?

Aucun commentaire:

Enregistrer un commentaire