Reading in a file with different data types

I am trying to read in a file that is similar to this:

push 10
pop
push 20
push 30
pop
push 10
push 50
push 20
push 20
pop

I am trying to make it so if it says push then it uses the pushfunction to push 10. And when it says pop it will pop off the top of the stack. Etc...

When you read in a file how do you make it read in the string, then use the integer?

1
2
3
4
5
6
7
8
9
10
11
12
getline(cin, fileAddress);
	ifstream textFile (fileAddress);

	//Tests the file
	if (textFile.fail())
	{
		cout << "File was not found"<< endl;
		system("PAUSE");
		exit (1);
	}
	else
		cout << "\nFile opened successfully" << endl;


That is what I have to read in the code but I am just stuck on how to store it then use it.

Thanks for the help!
This is using boost, which is a common third party library for C++.
1
2
3
4
5
6
7
8
9
10
11
12
13
string    current_line        = "";
vector<string> line_parts;
while (getline(file_, current_line)) {

  boost::split(line_parts, current_line, boost::is_any_of(" "));
  if (line_parts[0] == "pop")
   // call pop
  else if (line_parts[0] == "push") {
   // convert line_parts[1] to integer
   // call push function
  }

}


Alternatively, once you have the string representing the line you can split it using
current_line.substr().
Or, you could just use normal formatted extraction.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <stack>
#include <fstream>
#include <iostream>
#include <string>

void onPop(std::stack<int>&stack)
{
    if ( stack.empty() )
        std::cout << "ERROR:  pop on empty stack.\n" ;
    else
    {
        std::cout << "pop:\t" << stack.top() << '\n' ;
        stack.pop() ;
    }
}

void onPush(std::stack<int>& stack, int value)
{
    std::cout << "push:\t" << value << '\n' ;
    stack.push(value) ;
}

int main()
{
    std::stack<int> stack ;

    std::ifstream in( "stack.txt") ;

    std::string command ;
    while ( in >> command )
    {
        if ( command == "push" )
        {
            int value ;
            in >> value ;                    // error check would be good here.
            onPush(stack, value) ;
        } 
        else if ( command == "pop" )
            onPop(stack) ;
        else
            std::cout << "Unexpected command \"" << command << "\" encountered.\n" ;
    }
}
Awesome! I didn't use exactly what you wrote, but I used what you wrote to help me along in the process. Thanks so much!
Topic archived. No new replies allowed.