【问题标题】:Why am I getting extra character at the end of my output?为什么我在输出结束时会得到额外的字符?
【发布时间】:2015-07-17 20:29:44
【问题描述】:
int start = 0;
int end = 0;
string temp = "<sasadfsadfsady>40000</sadsfasdfsadflary>";
for (int i = 0; i < temp.length(); i++){

    if (temp[i] == '>' && start == 0)   //will only save first one
        start = i;
    if (temp[i] == '<')
        end = i-start;      //will be overwritten by the second one
}
temp.erase(temp.begin(), temp.begin()+start+1);
temp.erase(temp.begin() + end-1, temp.end());
cout << endl;
cout << temp << end;

输出:

400006

为什么最后是6?我不知道为什么会这样,请帮助我

【问题讨论】:

  • temp[i] == temp.length() 没有多大意义。 “如果字符串中的字符与字符串的长度具有相同的值”。那应该是if (i == temp.length()),这也是不可能的,因为无论如何你的循环都会在 i >= temp.length() 时终止。

标签: c++ string char output


【解决方案1】:
<< end

应该是这样的

<< endl

它现在输出 6,因为 int 变量 end 的值为 6。

【讨论】:

  • using namespace std; 的另一个危险。 std::end 将无法编译。
  • 实际上,现在我尝试了,我不只是得到一个编译错误。我得到了一大堆模板呕吐物!
  • 我现在无法访问代码,但 std 中可能有一个独立的模板函数 end()。
猜你喜欢
  • 2015-06-20
  • 1970-01-01
  • 1970-01-01
  • 2023-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-17
  • 1970-01-01
相关资源
最近更新 更多