【问题标题】:Implementation dependent outputs of strings字符串的实现相关输出
【发布时间】:2021-02-03 11:27:19
【问题描述】:

在下面的代码中,我在 mingw 编译器上只得到字符串 a 作为输出,但我在在线编译器上得到两个字符串作为输出。为什么我的系统没有得到适当的输出?

#include<iostream>
#include<cstring>

using namespace std;

int main(){
    string a="Welcome";
    string b="HelloWorld";
    for(int i=0;i<=b.length();i++){
        a.push_back(b[i]);
        
    }
    cout<<a<<endl<<b;

     

    return 0;   
}    

输出- 欢迎HelloWorld

【问题讨论】:

  • i&lt;=b.length() 是错误的。试试&lt;
  • 值得注意的是,您将一个零字节从b[b.size()] 复制到a。它定义明确,但可能你的终端在输出时会感到困惑。
  • @n.'pronouns'm。这并没有像“导致UB”那样错——错了。它只会将\0 附加到a。但这很可能不是故意的,是的。
  • @Scheff 它是为非常量版本定义的,只要你不修改那个空字节。

标签: c++


【解决方案1】:

您可以做的一件事是,您可以使用 cout.flush()。如果它不起作用,您可以执行 a+b 或者您可以使用 substr()

#include<iostream>
#include<cstring>
using namespace std;
int main(){
    cout.flush();
    string a="Welcome";
    string b="HelloWorld";
    cout<<a+b<<endl<<b;
    // cout<<a+b.substr(0,9);
    return 0;   
}  

【讨论】:

    【解决方案2】:

    我认为 cout.flush() 有时会在获得不需要的输出时有所帮助。所以,一旦你也可以在打印结果之前尝试一下。

    【讨论】:

      猜你喜欢
      • 2019-02-18
      • 2011-04-10
      • 1970-01-01
      • 1970-01-01
      • 2022-06-13
      • 1970-01-01
      • 1970-01-01
      • 2022-01-24
      • 1970-01-01
      相关资源
      最近更新 更多