views:

53

answers:

1

Hello,

I'm implementing a little command line parser. Let's say I have a command that requires 2 parameters. I want to let the user type all 3 strings (the command and 2 parameters) on one line, as well as on several lines. Currently I'm having something like this:

std::string command;
std::cin >> command;
std::cout << command << " entered\n";
std::string param1;
std::cin >> param1;
std::cout << param1 << " entered\n";
std::string param2;
std::cin >> param2;
std::cout << param2 << " entered\n";

Now I want to be able to detect that the user has just entered the command without any parameter, and output directions for that. I think after getting the command I should test if the line contains anything else and if it doesn't, ask the user to type more. I have tried with eof() and fail() but they do not work. How can I check for that then?

Thanks.

+6  A: 

If you want to read a line, then you should use std::getline. Once you have the whole line, you can break it up into words, however many there are.

UncleBens
+1 Beat me to it..
Mark B
well but I think I'm so close to it that I won't have to break the string and count the tokens
phunehehe
@phunehehe: As out have said you are implementing a command _line_ parser. Reading line by line (e.g. with `getline`) is the only sane way to achieve this. You can do word parsing with `>>` and an `istringstream` from the read line the same way as you are from `cin` at the moment.
Charles Bailey
in fact are you sure you really want to write a parser yourself? there are tools that can do it for you, potentially with less effort depending on the language you want to parse
jk
@Charles: that way seems to be more work: (1) get the line, (2) put it into a string stream, (3) get the tokens and check if it is `""`, (4) ask user to input more if it is. With my original approach, if it works, I only have to (1) check if there are more parameters coming and (2) if there are no more, spit out a string like `"Enter parameter 1: "`
phunehehe
@jk: thanks for the suggestion but this is part of a school assignment :)
phunehehe