Hello, how do I get Visual C++.NET to read a text file for which the columns have different lengths? I have a text file like so:
40 50 51
12 48 7
I want C++ to read in three vectors from this text file, of size 3, 5, and 2, respectively. Are there column "pointers" that can be used for this?
The numbers are nicely aligned, exactly as they appear, and I can use space, tabs, or other delimiters. This is because I am exporting the numbers from Excel to a text file for reading into C++, so I can modify their format. Some numbers will have 2 digits, others 3 or 4. Finally, I would like to do this without switching the columns around in the text file.
It look as as though you have a specific format to the data - I am assuming you will be producing a lot of these small files over time and just need to process them in a particular way, so do not need a genric way of reading the text file per se.
To read the textfile you use the StreamReader class, and the ReadLine() method - this will read the data one line at a time into a String.
You can then use the String methods IndexOf() (to find the next delimimter), Substring (to get specific parts of the string) and Trim() to remove excess whitespace.
To Convert the string to an Int you can use the Parse() method of the Int32 Class (once you have a string that only contains the number).
As this is C++ question the answer should use C++.
You haven't answered seymore15074's questions, which are vital to answering your question.
If the file is simply aligned within a specific number of spaces per column, then you can use the std::string::substr() function to split out the columns.
If the columns are separated by, say, a single tab, then you can use the getline() function to read each column:
1 2 3 4 5 6 7 8 9 10 11 12 13
// read the three columns
string columnstrings[ 3 ];
for (int i = 0; i < 3; i++)
getline( thefile, columnstrings[ i ], '\t' );
Once you have separated out a string containing a number, use a stringstream to extract the number:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
string numberstring = " 97";
// convert the number string to an actual number
// (invalid numbers --> zero)
if (!(istringstream( numberstring ) >> number)) number = 0;
If your file format is more sophisticated than fixed positions or a CSV, then you will need to ask your professor if you can simplify it.