file line by line and column by column

Write your question here.

Hi guys, i've a problem in reading a file line by line and column by column. I've a file txt with 65 columns and 20000 rows. I need to read it column by column and for each column save the sum of the elements into an array. For the same file than I've to read it line by line and do the same operation on each line so i think is better save it on a array. How can i do it?

Thanks,
Gaia

1
2
3
4
5
6
7
8
9
10
11
12
 int main(){


 array[i] = {0.}
for (i = 0; i < 20000; ++i){
 
 read the line and save it on an array[i]
 
 do operation on that array[i]
 
 save the result of the operation on an vector[i]
}
closed account (E0p9LyTq)
If I were doing it I'd read each line into an STL string, then get the individual column elements via stringstream input to add to the total sum of that line.

Rinse and repeat until you've read and dealt with all the lines in the file.

Whether you choose to store each line's sum in an array or other container is using what you are comfortable dealing with. I would probably use a pre-sized on creation vector.
Hello gaia96,

On line 4 you do not name a type for the variable. It looks like it should be of type double. The "i" for the size may work on your compiler, but not for every compiler. I believe that most of the newer compilers need a constant value for the size. From what I have seen "0.0" is used most often or you may be able to just use an empty set of {}s. In the end I would consider using a vector instead of an array.

For line 5 a while loop would be a better choice since you do not know how big the input file will be. while (inFile >> line). When there is nothing left to read, i.e., (EOF) the while condition will fail and the loop will end.

Then as FurryGuy suggests you can use stringstream to break up the line into what you need.

Line 7 is a bit confusing because you say read the line and save it on an array[i]. To read a whole line from a file you would have to use "std::getline(...)" which only works with a "std::string" and the array appears to be numeric, but the stringstream can compensate for that.

Having an idea of what the input file looks like would help instead of guessing at what could be there. Maybe five lines to work with.

Hope that helps,

Andy
Topic archived. No new replies allowed.