Cpp Reading a Dat File Onto an Array
Reading in .dat file, line by line, and storing in int array
I have a .dat file with numbers on each line. For example...
345
66478
43
60263
5212
8943346
...etc
I want to read in each line, 1 by one, and store each line into an alphabetize of an int array.
How would I do that? Too, would I first have to read through the file to come across how many lines of numbers there are, and then set up the array to that size?
I've been looking it upwardly and information technology seems like there are then many means to do this. Which i is the best for what I'chiliad trying to do?
Basically this is what I have so far...
| |
Last edited on
The nigh flexible fashion is to use a vector. If you've no idea how many values are in the file, this volition dynamically adjust as required.
| |
Awesome. Works perfect. Thank you!
Practice I need to shut the file when I'm washed with it?
In that location'south 1 trouble with it. When I effort to get it to cout all the numbers, it starts out fine, so stops half way through and can't consummate it.
| |
Last edited on
Well, the file will exist automatically airtight, in this case when the plan ends. In general, when the fstream goes out of telescopic, the file is airtight.
Personally I've always been in the habit of closing files when I'chiliad done, (it's usually required in various other programming languages) but since C++ streams will practise it for you lot, information technology'south by and large non necessary, except perhaps in specific circumstances. An instance might be when yous want to output some data to a file, shut it and so re-open it as an input file etc.
Nevermind, I got it. It should be vec.size -1, non vec[vec.size-one]
A pocket-size comment. Instead of i <= vec.size() - 1
you could put i < vec.size()
Information technology means the aforementioned, but a flake easier to read.
Thanks! You lot really helped a lot.
Topic archived. No new replies allowed.
Source: http://www.cplusplus.com/forum/beginner/117331/
Postar um comentário for "Cpp Reading a Dat File Onto an Array"