Solved

C++ redirecting input stream

Posted on 2014-03-09
6
360 Views
Last Modified: 2014-03-09
I am working on a project for my advanced programming class.  It is an expression interpreter.  I have a good portion of what I need.  I feel like I have gotten a lot done in a short amount of time and am now having an issue with redirecting the input stream to be a file, as opposed to the typical keyboard input.  In the present state of my program the user is asked for input:

int main()
{
	Expression* expression;
	char paren, comma;
	cout << "Enter expression: ";
	cin >> paren;
	expression = SubExpression::parse();
	cin >> comma;
	parseAssignments();
	cout << "Value = " << expression->evaluate() << endl;
	cin >> comma; // to wait for user input; allows the user to see what was printed before the window closes
	return 0;
}

Open in new window


I understand that I can use this method to read the input and display the lines of the input:

int main() {
	string line;
	ifstream myfile;
	myfile.open("CMSCProject3_Test.txt");
	if (myfile.is_open())
	{
		while (getline(myfile, line))
		{
			cout << line << '\n';
		}
		myfile.close();
	}
	else cout << "Unable to open file";

	return 0;
}

Open in new window


I am unsure of how to combine these two to interact with the program that I have created.  Where do I move the

 
        cin >> paren;
	expression = SubExpression::parse();
	cin >> comma;
	parseAssignments(); 

Open in new window



to so that it will operate?  Any assistance at all is greatly appreciated.  I feel like the answer is right in front of me, however I have not dealt with file input in C++ prior to this.  Thank you in advance for your assistance.
0
Comment
Question by:Autkast
  • 4
  • 2
6 Comments
 
LVL 86

Assisted Solution

by:jkr
jkr earned 500 total points
ID: 39916426
You'd basically replace 'cin' in your original code with the ifstream you opened, e.g. like

	ifstream myfile;
	myfile.open("CMSCProject3_Test.txt");
	if (!myfile.is_open())
	{
            return -1; // or any appropriate error code to indicate 'Could not open...'
        }
 
        myfile >> paren;
	expression = SubExpression::parse();
	myfile >> comma;
	parseAssignments(); 
           
// etc.                       

Open in new window

0
 

Author Comment

by:Autkast
ID: 39916475
Thank you for the prompt response!  I get a hang up when I am calling those 4 lines of code now though.  I'm assuming my problem is now in the other files associated with this main function (such as subexpression, parse, etc.).  Will I need to alter the input for these files as well to be from the text file object?  For example my parse:

string parseName()
{
    char alnum;
    string name = "";

    cin >> ws;
    while (isalnum(cin.peek()))
    {
        cin >> alnum;
        name += alnum;
    }
    return name;
}

Open in new window


Is there a certain way I make this new input viewable to the entire program that is accessed by this main function?
0
 
LVL 86

Accepted Solution

by:
jkr earned 500 total points
ID: 39916481
Yes, there is a way. Actually two ways, the more complex without global variables where you pass the file to each function involved as a parameter. The other one is a bit simpler, create a global variable as a surrogate for 'cin'. 'cin is usually declared as 'extern istream cin;', i.e. also a global variable. Now you'd create your own like

istream myin;

Open in new window


and asign it accordingly:

  if (!interactive) // don't use 'cin'
  {
	ifstream myfile;
	myfile.open("CMSCProject3_Test.txt");
  	if (!myfile.is_open())
	 {
            return -1; // or any appropriate error code to indicate 'Could not open...'
        }
 
        myin = myfile;
        myin >> paren;
	expression = SubExpression::parse();
	myin >> comma;
	parseAssignments(); 
           
// etc.                       
  }
  else
  {
     myin = cin; // use cin instead of a file
  }                                            

Open in new window

0
Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

 

Author Closing Comment

by:Autkast
ID: 39916624
Thank you for the help this evening, greatly appreciated.
0
 
LVL 86

Expert Comment

by:jkr
ID: 39916631
You're most welcome ;o)
0
 
LVL 86

Expert Comment

by:jkr
ID: 39916636
Just as a side note, the method of either passing thei fstream object to related methods or to the constructor of 'SubExpression' would be the preferred way...
0

Featured Post

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Whether you’re a college noob or a soon-to-be pro, these tips are sure to help you in your journey to becoming a programming ninja and stand out from the crowd.
Computer science students often experience many of the same frustrations when going through their engineering courses. This article presents seven tips I found useful when completing a bachelors and masters degree in computing which I believe may he…
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.
In this fourth video of the Xpdf series, we discuss and demonstrate the PDFinfo utility, which retrieves the contents of a PDF's Info Dictionary, as well as some other information, including the page count. We show how to isolate the page count in a…

770 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question