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:

(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.

Edited 4 Years Ago by sync101: n/a

I have managed to get started on the program.

Here is what my code looks like right now:

#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;

	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;
}

My question now is, how can I take in an input like this:

(color 0 0 0.1)(linewidth 2)

And get an output looking like this:

0 0 0.1 setrgbcolor
2 setlinewidth

So basically, how can I read the file one parentheses at a time?

You could try std::string::find (http://cplusplus.com/reference/string/string/find/) to find the first closing parenthesis, translate the first part, then go on.
So the code would look more or less like this:

string toTranslate;
getline(cin,toTranslate);
int lastPos=0;
int size=toTranslate.size();
do{
	int pos=toTranslate.find(')',lastPos);
	string current=toTranslate.substr(lastPos,lastPos-pos);
	// translate current here
	lastPos=pos+1;
}while(lastPos!=0)

Please debug it, as I wrote it in notepad without any checking.

This article has been dead for over six months. Start a new discussion instead.