Problem with std::string::find()

后端 未结 2 741
盖世英雄少女心
盖世英雄少女心 2021-01-28 11:15

I\'m in trouble using std::string::find(). I read strings from console through the following code:

 50   while(command.find(exitString) != 0) {
 51         std::         


        
相关标签:
2条回答
  • 2021-01-28 11:55

    You might be expecting that find returns zero when it found the string, kind of like the way strcmp works.

    But that's not how find works. find returns the first index of the found string, which might be zero, or might be something else if the string you're looking for is prepended with spaces, other strings, etc.

    If find doesn't find what you're looking for, it returns string::npos. So your if...else block should be checking to find if the strings were found or not found, not checking to see if they were at index zero. Like this:

    if(command.find(helpString) != string::npos ) {
              help();
          } else if /// ... etc...
    
    0 讨论(0)
  • 2021-01-28 12:10

    You are reading a line and then calling doSwitch() without checking if its exitString. In that case, when the input is exitString, else block at the end of doSwitch() function is executed, causing the program to print "Command Invalido" before exiting the loop.

    Is this what you observed?

    If its something else, please let us know for what input your code behaves incorrectly and what is the input and output.

    0 讨论(0)
提交回复
热议问题