-1

I'm trying to write a program that takes a .txt file of data, and displays it in a forms application (MVS 2010). My obvious first step is to take read the data. Unfortunately, I'm not very well versed in much of c++'s file i/o system, and I've been having a hard time figuring out how to do a various things (if anyone could recommend some literature on this, that would be nice).

What I want, is to translate the .txt text into a multidimensional array, where I can access each line with something like array[lineIndex]. The text file of data is formatted where one line is the data from one iteration of the code(from the robot), and the data on each line is separated by commas. As of now, I'm having trouble figuring out how to get each character ( ?? cin.get(file,character); ?? ), find the length of the .txt file (both lines and characters) and/or create an array that can increase in size (I don't know much about vectors either) as I add each line from the .txt file to the array.

I don't really need anyone to write the code for me, just give me a few pointers on what-does-what when you're accessing a .txt file. Code would be nice though. I learn best from example.

Here's what I have so far, which doesn't really work and wouldn't do much, but it's something.

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
    string line;
    char character;
    ifstream data;
    data.open("C:\\Example.txt");//opens the text file for input

    if (data.is_open())//if the .txt is opened
    {

        int i = 0;
        while (!data.eof())
        {
            cin.get(data,character);
            cout << character << endl;

            i++;
        }
        data.close();
        //printf("%c\n", line[1]);

        while (true) {}//pauses so I can see the window

    }
    else cout << "Unable to open file";

    return 0;

}
  • You seem to be talking about a single-dimensional array with indexes representing line numbers. – nhgrif Nov 24 '13 at 03:01
  • What does the file look like? That is, how do you tell where to break to the next element in your multidimensional array? – Zac Howland Nov 24 '13 at 03:59
  • I'll edit the post too, but the data text file is formatted where one line is the data from one iteration of the code, and the data on each line is separated by commas. – Maxwell-VII-IV Nov 24 '13 at 19:14

1 Answers1

3

Its simple to read a line into a string in c++, and build a vector of strings, if that what you want:

vector<string> lines;
string currLine;

ifstream data("text file.txt");

while(getline(data, getLine)) {
   lines.push_back(getLine);
}
RichardPlunkett
  • 2,998
  • 14
  • 14
  • This Is essentially what I wanted. I got hung up on how you would create an array without knowing the size of the .txt file. I didn't know about arrays. – Maxwell-VII-IV Nov 25 '13 at 16:01