1

我有以下代码:

#include <iostream>
using namespace std;
#include <string.h>

int main(){

 string track2;
 string Track2;
 string end_character("?");
 Track2={";80221000000100018A1301000000000000000?"};
 track2=Track2;

 cout<<"Track2={"<<Track2<<"}\n";

  if((track2.length()>=24 )  && (track2.find_first_not_of('0', 24) ==string::npos)){
     track2.erase (track2.begin()+24, track2.end());
  cout<<"\nTrack2={"<<track2<<"}\n";
  Track2=track2 + end_character;

  cout<<"\nTrack2={"<<Track2<<"}\n";
}
  else
     cout<<"Track2 has not more than 24 characters.\n";
}

我想首先检查字符串track2的长度,如果它大于或等于 24 个字符,那么如果第 24 个字符之后的其余字符 =0 并且最后一个字符 = . 然后我将在第 24 个字符的开头剪切字符串track2直到track2的结尾。之后,我将插入? 字符串 track2 末尾的字符并打印出来。这是预期的输出:

Track2={;80221000000100018A1301000000000000000?}

Track2={;80221000000100018A13010}

Track2={;80221000000100018A13010?}

但是我有一个问题,当我输入字符时,我无法进入我的 if 循环在我的字符串中。我的程序直接执行else循环。

有人可以帮我解决这个问题吗?谢谢

4

1 回答 1

2

像这样的东西怎么样:

if (Track2.length() > 24)
{
    auto question_mark_pos = Track2.find_first_not_of('0', 24);

    // If there is a character after the zeros AND
    // if that character is last AND
    // if that character is a question mark
    if (question_mark_pos != std::string::npos &&
        question_mark_pos == Track2.length() - 1 &&
        Track2[question_mark_pos] == '?')
    {
        // Get the first 24 characters of the string
        Track2 = Track2.substr(0, 24);

        // And append the special end character
        Track2 += end_character;
    }
}

经过测试,似乎可以工作,here

于 2012-12-14T10:41:10.410 回答