Translating input

Hi there, I am new to C++, and was wondering if someone could write an example program for me to work with.

What I would like to do is take input from stdin and then display the translate output to stdout.

Example:

Input:

1
2
(color 0 0 0.1) // These numbers can be any floating point numbers.
                // And there will always be parentheses. 


Output:

 
0 0 0.1 setrgbcolor


I think learning how to do this will be enough to get me on my way.

Any help will be greatly appreciated.
I'm assuming color is only one possible command and that you want to leave contingency for others.

First get the line
1
2
std::string Line;
getline(cin,Line)


Then delete the last parenthesis:
1
2
for (int i=0; i < Line.length(); i++)
    if (Line[i] == ')')  Line[i] == '\0');


Now put the line into a string stream:
1
2
std::stringstream iss;
iss << Line;


Now extract the outputs:
1
2
3
4
5
float R, G, B;
std::string command;
iss >> command;
if (command == "(color")
    iss >> R >> G >> B;
Thank you so much for the reply.

You are correct. Color is only one of commands.

Here are a couple of possible inputs:

Input:

1
2
3
(color 0 0 0.1)
(linewidth 2)
(translate 50 50)(rect -10 -10 20 20)


Output:

1
2
3
4
5
6
7
0 0 0.1 setrgbcolor
2 setlinewidth
40 40 moveto
60 40 lineto
60 60 lineto
40 60 lineto
40 40 lineto



Will work on the program and see what I can do. Thanks for the advice!
Last edited on
I seemed have gotten it working alright. Just need to tweak it a bit.

Here is what my code looks like so far:

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
#include <iostream>
#include <sstream>
#include <string>
#include <stdlib.h>
using namespace std;

int main()
{
	string line;
	string word;
	stringstream iss;
	ostringstream oss;
	float r, g, b, lw, t1, t2, r1, r2, r3, r4;
	
	cout << "%!PS-Adobe-3.1\n";
	while(getline(cin, line))
	{
		iss << line;
		iss >> word;
		
		if(word == "(color")
		{
			iss >> r >> g >> b;
			oss << r << " " << g << " " << b << " setrgbcolor\n";
		}
				
		else if(word == "(linewidth")
		{
			iss >> lw;
			oss << lw << " setlinewidth\n";
		}
				
		iss.str("");
	}
	
	cout.precision(2);
	cout << oss.str();	
	return 0;
}


Now when I give it the input:

1
2
(color 0 0 0.1)
(linewidth 2)


I get the output:

1
2
0 0 0.1 setrgbcolor
2 setlinewidth


So my question is how can I take an input like:

 
(color 0 0 0.1)(linewidth 2)


And get an output like this:
1
2
0 0 0.1 setrgbcolor
2 setlinewidth


Thanks for the help!
Last edited on
You could make ')' a delimiter. That is, the getline() function will treat this character as a seperator for a new line.

while(getline(cin, line, ')'))
Topic archived. No new replies allowed.