Function works when not in an if()

Hello all. Thank you for reading and or helping.

I am in my first C++ class and my terminology is/maybe wrong. This is part of and assignment which the program must find the GCD of 2 numbers.

I am using a function that will allow the user to enter the name of a file they wish to use. The problem is this works fine until i put the function call in an if() statement.

Anyone able to explain what i am doing wrong?



This function works when called like the following:
openFile(infile);


When used as below the " cerr<< "Input File Open Failed"; " always is output. There is no chance to enter a file name.

1
2
3
4
5
6
7
8
9
10
11
else if(choice == 'F')
	{
		//ask for the file name by using the "ifstream& openFile(ifstream& infile)" function.
		openFile(infile);

		while(getData(infile,v1, v2))
		{
			cout<<findGCD(v1,v2);
		}

	}


Here is the output:

This program will find the GCD of 2 integers.
Please enter "U" for user input or "F" for file input.
To quit press ( Ctrl + z )
Enter choice here: f
Enter input file name: Input File Open FailedPress any key to continue . . .






The function is
1
2
3
4
5
6
7
8
9
10
11
12
13
ifstream& openFile(ifstream& infile)
{
		string inputFileName;
		cout << "Enter input file name: ";
		getline (cin, inputFileName);
		infile.open (inputFileName.c_str());
		if(!infile)
		{
			cerr<< "Input File Open Failed";
			exit (-1);
		}
	return infile;
}
It looks like there is a newline being left in the stream after the user makes a choice. After you do cin>>choice, call cin.sync(); and see if that fixes the issue.
Yes that did fix the issue. Thank you.

FYI any one that wonders what cin.sync(); does check out this post

http://www.cplusplus.com/forum/beginner/45543/
Last edited on
Topic archived. No new replies allowed.