Solved

C++ redirecting input stream

Posted on 2014-03-09
6
350 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
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 

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

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

This article will show, step by step, how to integrate R code into a R Sweave document
This is an explanation of a simple data model to help parse a JSON feed
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
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.

757 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

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now