Reputation: 235
i am writing a program where i am trying to implement the following code:
int main(){
string inputcmd;
while (getline(cin, inputcmd)){
cout << "TYPE A COMMAND" << endl;
cin >> inputcmd;
cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');
if (inputcmd == "make"){
cout << "MAKING NEW PROJECT" << endl;
get_project(cin);
}
else if (inputcmd == "retrieve"){
cout << "RETRIEVING YOUR PROJECT" << endl;
}
}
return 0;
}
i am trying to use the cin.ignore property to clear the buffer of the newline character currently residing in the buffer at that given time, however when i try and compile it is giving me a bunch of gibberish compiler error? why is this how can i fix this?
Upvotes: 0
Views: 100
Reputation: 8961
You're using a strange combination of getline
and cin
... If you're using getline
, you don't have to call cin.ignore
at all. Don't mix both like you did or you will get confusing results.
This example propably runs like you want:
#include <string>
#include <iostream>
using namespace std;
int main(){
string inputcmd;
bool running = true;
while (running){
cout << "TYPE A COMMAND" << endl;
getline(cin, inputcmd);
if (inputcmd.substr(0, inputcmd.find(" ")) == "make"){
if(inputcmd.find(" ")!=string::npos){
inputcmd = inputcmd.substr(inputcmd.find(" ")+1);
cout << "MAKING NEW PROJECT: " << inputcmd << endl;
//get_project(cin);
}else{
cout << "make: not enough arguments" << endl;
}
}else if (inputcmd == "retrieve"){
cout << "RETRIEVING YOUR PROJECT" << endl;
}else if(inputcmd == ""){
running = false;
}
}
return 0;
}
Upvotes: 0
Reputation: 409166
You need to press an extra newline because you read the input twice. First with getline
and a second time with cin >> ...
.
If you can have arguments to the commands, I recommend you remove the cin >> ...
part, together with the cin.ignore()
call, and use only getline
and std::istringstream
:
std::cout << "Enter command: ";
while (std::getline(std::cin, line))
{
std::istringstream iss(line);
// Get the command
std::string command;
iss >> command;
if (command == "make")
{
...
}
...
std::cout << "Enter command: ";
}
This way, you can easily get the space-separated arguments to the command as well.
And yes, you have code to print the prompt twice, but that is a smaller and negligible problem in my opinion.
Or if you want to be even more general, use e.g. a std::vector
to store the command and arguments, and do something like
std::cout << "Enter command: ";
while (std::getline(cin, line))
{
std::istringstream iss(line);
std::vector<std::string> args;
// Get the command and all arguments, and put them into the `args` vector
std::copy(std::istream_iterator<std::string>(iss),
std::istream_iterator<std::string>(),
std::back_inserter(args));
if (args[0] == "make")
{
...
}
...
std::cout << "Enter command: ";
}
See e.g. these references:
Upvotes: 0
Reputation: 5741
Assuming you included
#include <string>
#include <iostream>
using namespace std;
Then I'm not getting any error.
Upvotes: 1