I simplified an issue I'm having in another program with the small program here.

The program is supposed to open the file with function openFile(). Then I want to initialize char a to the first character in the file via function accessFile() and output that character. My problem seems to be with this line:

fileInput >> a;

Because it outputs nothing for a. In the original program, I was setting up a switch case using a char variable (represented by a here), and it gave me "switch quantity not an integer".

I think I must be missing a key concept about using files, but I wasn't able to figure out what I'm doing differently from the example code I'm referencing. If someone can tell me what I'm doing wrong, I'd appreciate it.

(I'm a noob to C++, btw)

#include <iostream>
#include <fstream>

using namespace std;

void openFile()
{
	ifstream fileInput;
	fileInput.open("testInput.txt");
	
	if (!fileInput.is_open())
	cout << "Error. Could not open input file.\n" ;
}

void accessFile(ifstream& fileInput)
{
	char a;
	fileInput >> a;
	cout << a;
}

int main()
{
	ifstream fileInput;
	
	openFile();
	accessFile(fileInput);
	
	return 0;
}

Recommended Answers

All 2 Replies

I simplified an issue I'm having in another program with the small program here.

The program is supposed to open the file with function openFile(). Then I want to initialize char a to the first character in the file via function accessFile() and output that character. My problem seems to be with this line:

fileInput >> a;

Because it outputs nothing for a. In the original program, I was setting up a switch case using a char variable (represented by a here), and it gave me "switch quantity not an integer".

I think I must be missing a key concept about using files, but I wasn't able to figure out what I'm doing differently from the example code I'm referencing. If someone can tell me what I'm doing wrong, I'd appreciate it.

(I'm a noob to C++, btw)

#include <iostream>
#include <fstream>

using namespace std;

void openFile()
{
	ifstream fileInput;
	fileInput.open("testInput.txt");
	
	if (!fileInput.is_open())
	cout << "Error. Could not open input file.\n" ;
}

void accessFile(ifstream& fileInput)
{
	char a;
	fileInput >> a;
	cout << a;
}

int main()
{
	ifstream fileInput;
	
	openFile();
	accessFile(fileInput);
	
	return 0;
}

Anything you declare inside a function can't change anything outside a function, due to scope. They are treated as separate variables. So you have to pass fileInput by reference to openFile(), like you did with your accessFile function.

Awesome, thank you. That solved what I needed to move on to the rest of the program.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.