I am a beginning c++ student and need to read in a text file as shown below:

Orvilles's Acres, 114.8 43801
Hoffman's Hills, 77.2 36229
Jiffy Quick Farm, 89.4 24812
Houston Bayou Texas Home Grown Popcorn Inc., 124.7 65687

The criteria is to read characters to comma then read the double and int and compute a bar chart based on the numbers. I am stuck currently on the problem of reading in to a comma and limiting characters to 29 or less. Below is a sample of code fragment I have tried without success:

#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>

using namespace std;

int main()
	char x=' ';
	string Name=" ";
	int count=0, Jars=0;
	double Acres=0.0;
	fstream In;

	In.open("F:\\BonusProj.txt", ios::in);
	if (!In)
		cout<<"Error opening file";
		return 1;
		if (x != ',')
			Name = Name + x;
		if((x==',') || (count >= 29))
			Name=" ";
	return 0;

I attempted to use getline then parse the array to strip out the comma, double and int but was having problems getting valid numbers assigned. If someone could steer me in the correct direction it would be of immense help.

You seem interested in reading in a file until you reach a delimeting comma. In this case, I recommend use of getline().

There are a few different getline() functions floating around in the c++ world. The one we are using (and most popular in file i/o) is derived from the <string> library:


string town[20];
double ave_temp[20];
int population[20];

int i=0;
while(getline(In, town[i], ','))
     //these are "white space" delimeted
     in >> ave_temp[i];
     in >> population[i];

I attempted to use getline then parse the array to strip out the comma,

Being the astute CS student that you are, I am sure that you've already studied the documentation for the getline() function and found out that it extracts and discards any delimeting characters:


function<string>istream& getline ( istream& is, string& str, char delim );
istream& getline ( istream& is, string& str );
Get line from stream

Extracts characters from is and stores them into str until a delimitation character is found.

The delimiter character is delim for the first function version, and '\n' (newline character) for the second. The extraction also stops if the end of file is reached in is or if some other error occurs during the input operation.

If the delimiter is found, it is extracted and discarded, i.e. it is not stored and the next input operation will begin after it.

So today, we used a version of the overloaded <string> library function called getline(). The version we used today has 3 arguments, the last of which we can supply a single char as a delimeter. We then used the <fstream> extraction operator >> to read in the file until a white space/newline/end of file is reached into data types specific to our chosing (in this case, a double followed by an int).