Trying to open and read a file.

Hi All, I know I'm new here and a 'beginner' by many peoples standards, so I shall apologise in advance for the ensuing rant.

Arrrgggghhhh. This is like wading through treacle. Honestly, talk about making an easy job unbelievably hard work. No wonder I stick to VB. Yes I know that's probably a swear word here, but what I'm trying to achieve took me 3 minutes in VB and, up to press, I've gone through over 8 hours and goodness knows how many forums and web sites trying to find the answer for C++. Sorry, deep breaths, calm blue ocean.

It should be a simple task. I have a text file which contains three integers, comma separated in rows like this:

22,45,2
34,5,6
21,5,0
and so on...

I'm using Borland c++ builder, and would like to use the TOpenDialog control to allow the user to select the file, then place the contents in an array.
I've tried so many variations of code I've lost track. Everything I try throws some sort of error.

To explain better here's how I did it in VB:

Private Sub cmdLoad_Click()

Dim strFile As String
Dim intLoop As Integer
Dim DataIn(2,256) As Integer

dlgMain.ShowOpen
strFile = dlgMain.FileName

Open strFile For Input As #1

For intLoop = 1 To 256
Input #1, DataIn(0, intLoop), DataIn(1, intLoop), DataIn(2, intLoop)
Next
Close #1
End Sub


Simple. Please could someone show me how to do this? The bruise on my forehead is getting quite big now!

Thanks

Last edited on
If the numbers was separated by space it would be a little easier.
1
2
3
4
5
6
std::ifstream file("filename.txt");
int n1, n2, n3;
while (file >> n1 >> n2 >> n3)
{
	// do something with the three numbers
}


If you really want comma separated numbers you can read the commas into a char variable and test if they are equal to ','.
1
2
3
4
5
6
7
8
9
10
11
12
std::ifstream file("filename.txt");
int n1, n2, n3;
char c1, c2;
while (file >> n1 >> c1 >> n2 >> c2 >> n3)
{
	if (c1 != ',' || c2 != ',')
	{
		// error, number is not separated by comma
		break; // stop the loop
	}
	// do something with the three numbers
}
Last edited on
> what I'm trying to achieve took me 3 minutes in VB

It doesn't take any longer in C++. A few lines less actually.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <fstream>

void  cmdLoad_Click()
{
    // Dim DataIn(2,256) As Integer
    int DataIn [3] [256] = { {0} } ;

    // Open strFile For Input As #1
    std::ifstream file( "put the file name here" ) ;

    // For intLoop = 1 To 256
    for( int i=0 ; i<256 ; ++i )
    {
        // Input #1, DataIn(0, intLoop), DataIn(1, intLoop), DataIn(2, intLoop)
        char comma ;
        file >> DataIn[0][i] >> comma >> DataIn[1][i] >> comma >> DataIn[2][i] ;
        // note the absence of any error checking. A la VB!
    }
}


Hadn't seen Peter87's post when I wrote this. Sorry about the duplication.
Last edited on
Thanks for the replies, I really do appreciate it.

Now the only thing I'm struggling with is getting the file name into the 'put file name here'

Everything I try results in an error. Again looking at it from a VB perspective, the TOpenDialog1-> Filename looks like a property of TOpenDialog so I expected to be able to drop it straight into a string:

string strFilename;
strFilename = TOpenDialog1-> Filename;

But that just throws an error.....

Yeh, no error checking in my sample for clarities sake ;-)
Hey Electro. I don't quite understand your last question but here is some nice, readable code to solve your original question. Walkthrough this code and it should be clear what is going on.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    ifstream input; //object to read data from the input file
    int num1, num2, num3; //variables to store the three integers in each line
    char ch; //garbage variable to store the commas in the file

    //open the input file
    input.open("inFile.txt");

    //If the file could not be opened for whatever reason, terminate the program
    if(!input)
    {
        cout << "The file could not be opened. Terminating program..." << endl;
        return 0;
    }

     //Continue reading data from a file until the end of file is reached
    while(!input.eof())
    {
        //Get num1, then the comma, then num2, then the comma, then num3
        input >> num1 >> ch >> num2 >> ch >> num3;

        //Output the three numbers to the console
        cout << num1 << " " << num2 << " " << num3 << endl;
    }

    return 0;
}
By the way, if you want the user to enter the name of the file (I think this is what you mean?), you can store the file name in a string variable. The only thing is that the ifstream member function open only accepts a cstring, so you have to convert the string to a cstring like so..

1
2
3
4
5
6
7
ifstream input;
string fileName;

cout << "Enter the name of the input file: ";
cin >> fileName;

input.open(fileName.c_str());


The string member function c_str converts a string object into whats knows as a cstring.
Last edited on
Or you could do it like:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <string>
#include <fstream>

int main()
{
	std::fstream file;
	std::string filename;

	std::cout << "Enter filename: ";
	std::getline( std::cin, filename, '\n' );

	file.open( filename, std::ios::in );

	if( file.is_open() )
	{
		std::cout << "File is open\n";

		file.close();
	}
	else
		std::cout << "Unable to open file...\n";
   
	return 0;
}


When using files, I've never used a c-string to open a file.

EDIT:
What ever you type in to the console, i.e:
textfile.txt

Make sure it exists before trying to open it. Or the above code if( file.is_open() ) will return false.
Last edited on
Topic archived. No new replies allowed.