为什么没有分配零字符后的内容?

时间:2017-11-22 12:37:50

标签: c++ string

#include<iostream>
#include<string>
using namespace std;
int main(){
    string a;
    a="this is string\0 this part not assigned why?";
    cout<<a;
    cout<<"sth";
cout<<endl;
    a.push_back('\0');
        cout<<a;
        cout<<"sth";
}

问:为什么\0未分配给字符串a后的内容?

6 个答案:

答案 0 :(得分:2)

在C ++中, C风格的字符串以零字符终止。

此代码:

a = "this is string\0 this part not assigned why?";

您正在调用函数string& string::operator =(const char*)通过出现零来确定字符串的结尾。当然,当它看到\0时,它认为字符串结束了。

FYR,如果您想要换行符,请使用\n而不是零字符。

答案 1 :(得分:2)

std::string变量的空值assigningstring literaloperator""s。字符串文字在空终止符\0处获得 cut ,因为它的类型为const char[],因此生成的字符串为:

  

this is string

如果要保留整个字符串,然后使用字符串reference,请添加s后缀并在启用C ++ 14支持的情况下进行编译。这将形成类型为std::string的字符串文字:

std::string a = "this is string\0 this part not assigned why?"s;
std::cout << a;

结果现在是:

  

this is string this part not assigned why?

{{3}}州(强调我的):

  

使用包含嵌入式'\ 0'的字符串文字进行初始化   字符使用重载(5),在第一个空值处停止   字符。通过指定不同的构造函数可以避免这种情况   或者使用运算符“”

答案 2 :(得分:2)

表达式a = "this is string\0 this part not assigned why?"使用std::string赋值运算符将const char*作为参数。 (const char[]字面值衰减到const char*。)

该运算符被定义为在遇到第一个NUL终结符时停止读取。在您的情况下,这将是输入文字中的显式\0,而不是最后的隐式。{/ p>

答案 3 :(得分:1)

C和C ++(对于c风格的字符串)用'\0'字符标记字符串的结尾。假设"hi"为字符串。它包含三个字符,实际上是hi\0

答案 4 :(得分:1)

要将整个字符串文字用作字符串变量的值,您可以传入字符串文字的长度。这也可以包括显式和隐式'\0'字符。

#include <cstddef>
#include <string>
#include <iostream>

using std::string;
using std::cout;
using std::endl;

template<typename T, std::size_t size>
std::size_t GetArrayLength(T(&)[size]){
  return size;
}

int main() {
  string a;
  char const s[] = "this is a string\0 this part not assigned why?";
  a = string{s, GetArrayLength(s)};
  cout << a << endl;
  for (auto c : a) {
    if (c >= ' ' && c <= '~')
      cout << c;
    else
      cout << "<" << (int)c << ">";
  }
  cout << endl;
  return EXIT_SUCCESS;
}

答案 5 :(得分:-1)

’\0’表示字符串的结尾,因此大多数函数都不会将其后面的任何字符视为字符串的一部分,包括cout

考虑到这些函数需要有一种方法来知道字符串中的走多远(否则它们将继续通过所有内存),并且’\0’是商定的结束标记。

如果您需要换行符,请使用’\n’