Ok, I have here a program where I'm trying to read a specific line from a file, store it as a string of characters, and then, if the right string of characters is stored, perform specific tasks. When I run this program I only get 11 of the characters stored and the wrest appear to be junk when I output what is stored to the screen.

To run the program, you key in the file name to be read as the second argument.
Try running it yourself, where the file your reading from has more than one line and each line has more than 11 characters and you'll see what I mean. I have no idea why its doing this.

 * read.cpp
 *  Created on: Oct 28, 2008
 *      Author: Jake

using std::cout;
using std::endl;
using std::ifstream;
/*Simple program that takes a file name from the user as
 * the second argument, reads that file, and then outputs
 * a chose line of it onto the screen.*/
int main(int argc, char* argv[])
	ifstream inputfile;
	inputfile.open(argv[1]); //open the file
	if(!inputfile) //if the file was not opened, display error message and end program with an error
		cout << "ERROR: FILE COULD NOT BE READ" << endl;
		static int j=0; //holds number of characters per line
		static int i = 1; // want i to give the number of the current line
		char c;
		char* lineholder = new char[j];
		while(!inputfile.eof()) //the file window won't advance unless you advance it, if it doesn't advance this loop will never end
			if(inputfile.peek()=='\n') //if an end of line is reached and its the right line print the characters on the current line otherwise reset the string so it only holds characters on next line
				++i; //line number increments before going to the next line
				inputfile.get(c); //same as (put the value at the file window into *c, advance the file window to the next component)
			cout << lineholder;
		delete [] lineholder;
8 Years
Discussion Span
Last Post by jakethesnake86

your program does not allocate any memory for the line. And your program does way too much work! This is all that is needed.

std::string line;
int i = 0;
while( i < 7 && getline(inputfile, line) )
cout << line << "\n";
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.