0

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;
}
2
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by myk326
0

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.

0

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

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.