0

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?

Edit:

I clearly mentioned in the question that I am looking for short and simple way in C++ that will:

  • stip the read line to remove any leading and trailing characters including end line python strip() does that. I took a look at What's the best way to trim std::string?, the C++ code for stripping will be larger than the entire python program.
  • split the resultant string and put them into two vectors as floats.

The other answers such as How can I read and parse CSV files in C++? do not address these points.

ewrf324
  • 11
  • 1
  • @ BoPersson edited the question. – ewrf324 Jan 28 '18 at 23:10
  • @BoPersson: The dupe you chose is about a much more complex task than what ewrf324 is asking for here, and the solutions are also correspondingly overcomplicated for the simple task at hand here. I really don't see much point in having this question closed as a dupe, especially since it already has a perfectly valid answer (which would *not* be a valid answer to the [other question](https://stackoverflow.com/questions/1120140/how-can-i-read-and-parse-csv-files-in-c)). – Ilmari Karonen Jan 30 '18 at 05:15

1 Answers1

1
float a, b;
char comma;
vector<float> vec1, vec2;
ifstream in("f1.txt");
while (in >> a >> comma >> b)
{
    vec1.push_back(a);
    vec2.push_back(b);
}

Untested code, and no error handling.

john
  • 85,011
  • 4
  • 57
  • 81