0

So, I made a program that will let a user enter a command, like print message and it will show him the message he entered. For example, if he types in: print Hello, the console's output will be Hello.

Now, here's my code:

#include <iostream>
using namespace std;

int main()
{
string command;
start:
cout << ">>> ";
cin >> command;
if (command.substr(0,5) == "print")
{
    if (command.substr(6,command.end) != "")
    {
        cout << command.substr(6,command.end);
        goto start;
    }
    else
    {
        cout << "Usage: print text";
        goto start;
    }
}
}

The thing is I get an error:

no matching function for call to 'std::basic_string::substr(int, )'|

and I'm not sure if I specified the substring length correctly. I wanted the first if to check if the first five words were print.

Mateaș Mario
  • 77
  • 1
  • 6

3 Answers3

2

Try replacing command.end with command.length().

Sidenote: It is good programming style to use the break, continue, and return statements instead of the goto statement whenever possible.

benwrk
  • 368
  • 2
  • 7
2

Your error is that you are providing command.end as an argument to the substr function which is not a valid parameter. It looks like you want to print the rest of the contents of command, in which case you can just call command.substr(6).

tweej
  • 832
  • 4
  • 16
  • Error after I write: "print Hello": `terminate called after throwing an instance of 'std::out_of_range' what(): basic_string::substr: __pos (which is 6) > this->size() (which is 5)` – Mateaș Mario Dec 02 '17 at 11:44
  • cin skips whitespace. Use the std::noskipws flag, cin.get, or std::getline: https://stackoverflow.com/questions/2765462/how-to-cin-space-in-c/2765613 – tweej Dec 02 '17 at 18:47
1

First of all, you forgot to write #include <string>. Also it would be better not to use goto operator and a lot of magic numbers (5, 6 in your code). For reading string (from standard input) that can contain spaces you should use getline. In substr you omit the second argument if we want to get all characters until the end of the string.

I have refactored your solution and have the following code:

#include <iostream>
#include <string>

using namespace std;

int main()
{
  string command;
  string prompt("print");
  cout << ">>> ";
  while(getline(cin, command) &&
        command.size() >= prompt.size() && 
        command.substr(0, prompt.size()) == prompt)
  {                 
     if (command.size() > prompt.size())
     {
       cout << command.substr(prompt.size() + 1) << endl;
     }
     else
     {
       cout << "Usage: print text" << endl;
     }
    cout << ">>> ";
  }
  return 0;
}
Igor
  • 477
  • 5
  • 13