首页 > 解决方案 > 以下两个字符串案例有什么区别

问题描述

我正在尝试将值分配给字符串然后访问它,但是对于第一种情况,我没有得到想要的输出....

#include <iostream>
#include <string>
using namespace std;
 
int main(){
      
      string abc;

      abc[0] = 'm';

      cout << "str1 : " << abc    << endl;
      cout << "str1 : " << abc[0] << endl;

      //-----------------------------------

      string xyz;

      xyz = "village";

      cout << "str2 : " << xyz    << endl;
      cout << "str2 : " << xyz[0] << endl;

      return 0;
}

输出应该是:

str1 : m
str1 : m
str2 : 村
str2 : v

但实际上它是:

str1 :
str1 : m
str2 : 村
str2 : v

标签: c++arraysstringchar

解决方案


在第一种情况下,您将null-terminator(每个字符串在末尾都有,以标记结束)替换为m,并且可能导致大量随机输出,如果不是SIGSEG崩溃和/或未定义的行为。

解决方案

数组样式

std::string myVariable;

// ...

myVariable.resize(3, '\x0');
myVariable[0] = 'm';
myVariable[1] = 'a';
myVariable[2] = 'x';
// And index 3 is already null-terminator (no need to set manually to zero).

你应该做什么

如果速度不是问题,而您只想要稳定性和易用性,请尝试以下操作:

abc += 'm';

或者

abc.append(1, 'm');


推荐阅读