Reading off a string array from a text file.

Hello, I am attempting to read off a specific portion of a string based on the input of the user. Each time I run this program, I get an exception handling error. As of right now I'm starting off easy by just wanting it to read me the Genre of a given film. Is there anyone who can help or has any suggestion?
Here is the text file.
Amadeus, Drama, 160 Mins., 1984, 14.83
As Good As It Gets,Drama,139 Mins.,1998,11.3
Batman,Action,126 Mins.,1989,10.15
Billy Elliot,Drama,111 Mins.,2001,10.23
Blade Runner,Science Fiction,117 Mins.,1982,11.98
Shadowlands,Drama,133 Mins.,1993,9.89
Shrek,Animation,93 Mins,2001,15.99
Snatch,Action,103 Mins,2001,20.67
The Lord of the Rings,Fantasy,178 Mins,2001,25.87
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
34
35
36
37
38
39
40
41
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
	string dvd;
	cout << "Which DVD would you like information on?\n";
	cin >> dvd;
	ifstream inStream;
	ofstream outStream;
	inStream.open("datafile.txt");
	if(inStream.fail())
	{
		cout << "Input file opening failed.\n";
		system("PAUSE");
		exit(1);
	}
	 while(!inStream.eof())
	 {
		 if(dvd == "Amadeus")
		 {
			 for(int i=0; i < 100; i++)
			 {
				 string output[1];
				 inStream >> output[i];
				 if(output[i] == "Amadeus")
				 {
					
					cout<< "The Genre of the film: "        <<output[sizeof(dvd)+1];//I'm using size in an attempt to gain acces to Drama
					string dvdGenre = output[sizeof(dvd)+1];
					
				 }

			 }
		 }
	 } inStream.close();
	 outStream.close();
	 system("PAUSE");
	 return 0;
}
Your program is crashing because you create an array of strings called output with a size of one, and then try and access elements 0-99, obviously out of bounds. Why don't you load all the movies into memory, then print out the correct info based user input instead? Also, use getline(cin, dvd) to get the movie name from the user, that way you get the spaces from the name as well.

I'll give you a hint on how to parse the file. getline ( http://cplusplus.com/reference/string/getline/ ) can take a deliminator character other than \n to stop getting input at, and can read from files. Also, notice how there is a comma (',') in between all fields (except the last, which is '\n'). You can use those commas, in conjunction with getline(file, string, ',') to read all the data fields for each movie.
Topic archived. No new replies allowed.