I have a file called numbers.dat that consists of 20000 random numbers. I need to create an array in my *.cpp file whose elements are the numbers from the numbers.dat file. I am sure this is basic, however, nothing I have found online has answered my question. Thank you for any help.
Asked
Active
Viewed 2,172 times
-4
-
1To be able to answer this question in a way that is meaningful to you, we need to understand where you are stuck... Don't you know how to open a file, how to read numbers from a file or how to add them to a vector/array? If it's "all of the above", there is a great list of reading material here: http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list – Mats Petersson Jul 10 '13 at 23:39
-
is your question about how to read the contents of the dat file, or how to convert the content string of numbers into an array? – Lochemage Jul 10 '13 at 23:39
-
In addition to the above comments, what is the file format? Not all .dat files are created equal(ly formatted) :-) – Karl Nicoll Jul 10 '13 at 23:40
-
i think `*.cpp` won't compile except it is the only cpp file in directory. – user1810087 Jul 10 '13 at 23:45
-
Most of the time, if you are in the right directoy, `*.cpp` will compile... ;) – Mats Petersson Jul 10 '13 at 23:48
-
1You haven't provided any effort to solve this yourself, and no description of the format of your file (other than that it consists of 20000 random numbers). Please search here for `[c++] read file array` and do some research, and then post at least a concise description of your file, the code you've tried that isn't working, and ask a specific question related to that information. This isn't a "Here's a vague description of what I need. Please post the code." site. – Ken White Jul 11 '13 at 00:12
1 Answers
0
You need to provide a lot more information if you expect a useful answer, but to get you started, here's a very simple example of what you can do.
I'm assuming that your file is a text file (doesn't matter what the extension is; a text file is one that you can open in notepad and read its contents.)
#include <fstream>
#include <vector>
int main ()
{
std::vector<int> data;
std::ifstream fin ("numbers.dat");
int temp = 0;
while (fin >> temp)
data.push_back (temp);
// Here you have your data in the "data" vector.
return 0;
}
The above code reads however many integers that are in a file named "numbers.dat". These integers must be separated with some whitespace (space characters, tabs, new lines, etc.) but not things like commas and semicolons.
If you need to read your numbers from a binary file, write a comment and I'll extend my answer.

yzt
- 8,873
- 1
- 35
- 44