Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

C++ redirecting input stream

Posted on 2014-03-09
6
Medium Priority
?
391 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
[X]
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
  • 4
  • 2
6 Comments
 
LVL 86

Assisted Solution

by:jkr
jkr earned 2000 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 2000 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
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

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

Ask an Anonymous Question!

Don't feel intimidated by what you don't know. Ask your question anonymously. It's easy! Learn more and upgrade.

Question has a verified solution.

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

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 …
Article by: evilrix
Looking for a way to avoid searching through large data sets for data that doesn't exist? A Bloom Filter might be what you need. This data structure is a probabilistic filter that allows you to avoid unnecessary searches when you know the data defin…
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.
Suggested Courses

636 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