2

I'm working on a command line interface. The user enter a commands such as

This would add a "song" with the -s flag

add -s TITLE ARTIST 

This would add an "album" with a -a flag

add -a TITLE ARTIST

There are different flags and different commands like delete as well.

I've done this to evaluate the commands and flag, however I'm having trouble getting the rest of the string. The user input is taken in as an array of char, which I convert into a string.

  if (inputString.substr(0, 3) == "add"){
    if (inputString.substr(4, 5) == "-s"){
      cout << "TEST: ADD SONGS" << endl;
      //PROBLEM IS THIS LINE
      cout << inputString.substr(6, MAX_LENGTH) << endl;
    }

Whenever I get the command + action flag, I'd like to run a new function using the rest of the string to actually add the information into the database.

There is no problem when I typeadd -s The program knows I want to add a song from evaluating the first characters. However if I type in more such as "add -s "Sorry" "Justin Bieber" The program doesn't even acknowledge that the add -s flag was run.

Can someone explain why this is and how I can change it? Stuck on it for a while now.

user1692517
  • 1,122
  • 4
  • 14
  • 28
  • As a note, doing this yourself is going to be a whole world of hurt. Have you considered using a library like [Getopt](https://en.wikipedia.org/wiki/Getopt)? It's practically universal in C. – tadman Oct 10 '17 at 02:41
  • You could improve your question a lot with a [mcve]. What have you observed in your debugger? – Tas Oct 10 '17 at 02:43
  • I would consider using a string splitting algorithm: https://stackoverflow.com/questions/236129/most-elegant-way-to-split-a-string – Galik Oct 10 '17 at 02:53

1 Answers1

1
if (inputString.substr(4, 5) == "-s"){

The second parameter to substr() is the character count. This extracts (up to) 5 characters from the string, starting at offset 4.

However if I type in more such as "add -s "Sorry" "Justin

Ok, so using my fingers to count off to offset 4, that is, indeed, the '-' character. Then, extracting five characters starting at that position arrives at the following string:

-s "S

I count that as five characters. That's what the substr() returns. Comparing this for equality with the string "-s" obviously fails.

You should take this as a convenient opportunity to learn some debugging skills. Had you added something like this:

std::cout << inputString.substr(4, 5) << std::endl;

Right before the second if statement, I'm confident you would've figured this out all by yourself.

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148