I have a file with data listed as follows:
0, 2, 10 10, 8, 10 10, 10, 10 10, 16, 10 15, 10, 16 17, 10, 16
I want to be able to input the file and split it into three arrays, in the process trimming all excess spaces and converting each element to integers.
For some reason I can’t find an easy way to do this in c++. The only success I’ve had is by inputting each line into an array, and then regexing out all the spaces and then splitting it up. This entire process took me a good 20-30 lines of code and its a pain to modify for say another separator(eg. space), etc.
This is the python equivalent of what I would like to have in C++:
f = open('input_hard.dat') lines = f.readlines() f.close() #declarations inint, inbase, outbase = [], [], [] #input parsing for line in lines: bits = string.split(line, ',') inint.append(int(bits[0].strip())) inbase.append(int(bits[1].strip())) outbase.append(int(bits[2].strip()))
The ease of use of doing this in python is one of the reasons why I moved to it in the first place. However, I require to do this in C++ now and I would hate to have to use my ugly 20-30 line code.
Any help would be appreciated, thanks!
There is really nothing wrong with fscanf, which is probably the fastest solution in this case. And it’s as short and readable as the python code: