Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

C++ redirecting input stream

Posted on 2014-03-09
6
369 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
Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

 

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

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

This is about my first experience with programming Arduino.
Container Orchestration platforms empower organizations to scale their apps at an exceptional rate. This is the reason numerous innovation-driven companies are moving apps to an appropriated datacenter wide platform that empowers them to scale at a …
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.
With the power of JIRA, there's an unlimited number of ways you can customize it, use it and benefit from it. With that in mind, there's bound to be things that I wasn't able to cover in this course. With this summary we'll look at some places to go…

840 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