Need help opening text file?

Hi there! I am in an "intro" C++ course and am having trouble with a section of my current project.

We are required to open a text file, read the data from that file, and print it back. However, we are supposed to let the user input the name of the file that is to be opened. This is the code I have so far. It is not opening anything.

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
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

const int NUM_QUESTIONS = 30;
typedef char CharArray[NUM_QUESTIONS];
string fileName;

void printAnswerKey(CharArray);
void ReadAnswers(CharArray); 
string GetFileName();
void OpenFile(ifstream&);


void printAnswerKey (CharArray answerKey) // to output the answer key
{
	ifstream inFile;

	cout << "Please enter the file name to open -->";
	cin >> fileName;
	
	
	inFile.open(fileName.c_str());
	
	for (int i = 0; i < NUM_QUESTIONS; i++);
	     cout << answerKey[NUM_QUESTIONS] << " ";
}


Any help would be greatly appreciated!
Thank you so much in advance!
Is the file you are trying to open in the same directory as the executable?

Looks like it's working, had to add some code to test it but this might help.

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
42
43
44
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

const int NUM_QUESTIONS = 30;
typedef char CharArray[NUM_QUESTIONS];
string fileName;

void printAnswerKey(CharArray);
void ReadAnswers(CharArray); 
// string GetFileName();
void OpenFile(ifstream&);


void printAnswerKey (CharArray answerKey) // to output the answer key
{
	ifstream inFile;

	cout << "Please enter the file name to open -->";
	cin >> fileName;
	inFile.open(fileName.c_str());

// Added
    if (inFile.is_open())
	{
	cout << "file open";
	}
	else
	{
	cout << "file not open";
	}
	
		
//	for (int i = 0; i < NUM_QUESTIONS; i++);
//	     cout << answerKey[NUM_QUESTIONS] << " ";
}

int main()
{
	char* x;
	printAnswerKey(x);
	return 0;
}
Topic archived. No new replies allowed.