简体   繁体   English

无法使用 C++ 在同一个字符串上多次使用 string.substr(x, y) ?

[英]Unable to use string.substr(x, y) multiple times on the same string with c++?

I'm working on a command line interface.我正在研究命令行界面。 The user enter a commands such as用户输入命令,例如

This would add a "song" with the -s flag这将添加带有-s标志的“歌曲”

add -s TITLE ARTIST 

This would add an "album" with a -a flag这将添加一个带有-a标志的“专辑”

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.每当我获得 command + action 标志时,我都想使用字符串的其余部分运行一个新函数,以将信息实际添加到数据库中。

There is no problem when I type add -s The program knows I want to add a song from evaluating the first characters.我输入add -s时没有问题程序知道我要通过评估第一个字符来添加歌曲。 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.但是,如果我输入更多内容,例如“ add -s "Sorry" "Justin Bieber"该程序甚至不承认 add -s 标志已运行。

Can someone explain why this is and how I can change it?有人可以解释为什么会这样以及我如何改变它吗? Stuck on it for a while now.现在坚持了一段时间。

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

The second parameter to substr() is the character count. substr()的第二个参数是字符数。 This extracts (up to) 5 characters from the string, starting at offset 4.这从字符串中提取(最多)5 个字符,从偏移量 4 开始。

However if I type in more such as "add -s "Sorry" "Justin但是,如果我输入更多内容,例如“add -s”Sorry“Justin

Ok, so using my fingers to count off to offset 4, that is, indeed, the '-' character.好的,所以用我的手指倒数到偏移量 4,也就是“-”字符。 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.这就是substr()返回的内容。 Comparing this for equality with the string "-s" obviously fails.将此与字符串“-s”的相等性进行比较显然失败了。

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.就在第二个if语句之前,我相信你会自己弄清楚这一切。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM