【问题标题】:Convert a char array to a string and store the string?将char数组转换为字符串并存储字符串?
【发布时间】:2018-07-04 22:29:44
【问题描述】:

我想使用从 char 数组转换而来的字符串,但是当我编辑我的 char 数组时,字符串似乎发生了变化。我意识到两者都指向内存中的相同位置,并试图将字符串存储在一个新字符串中。但是,当我编辑 char 数组时,即使它们具有不同的内存位置,新字符串仍然会发生变化。编辑原始数组时如何不更改新字符串?顺便说一句,我正在使用 Dev C++。

char str[] = "Test test";
string z(str);
string s = z;
printf("%s, str[]'s location = %d, z location = %d, s location = %d", s, str, z, &s);
str[0] = 'n';
printf("\n%s, str[]'s location = %d, z location = %d, s location = %d", s, str, z, &s);

【问题讨论】:

  • 你用的是什么编译器?
  • 你打印的东西不正确,你的警告应该告诉你。阅读printf 的手册,或者最好使用cout
  • 使用 cout,而不是 printf。你已经用错了!
  • %d 用于打印整数值,std::string 无法解析为使用printf() 进行格式化。你为什么要使用printf() 将控制台输出到 C++ 中?请改用std::cout
  • @TheDude 好吧,OP 可以使用.c_str()

标签: c++ arrays string dev-c++


【解决方案1】:

我想使用从 char 数组转换而来的字符串,但是当我编辑我的 char 数组时,字符串似乎发生了变化。

编辑 char 数组时不会以任何方式修改 std::string。

我意识到两者都指向同一个位置

它们不指向同一个位置。

并尝试将字符串存储在新字符串中。但是,当我编辑 char 数组时,新字符串仍然会发生变化

另一个 std::string 也没有被修改。

编辑原数组时如何不更改新字符串?

就像您在示例中所做的那样:str[0] = 'n';


您的问题是程序具有未定义的行为。 printf 对给出的参数类型有严格的要求。您的程序不满足这些要求:

"\n%s, str[]'s location = %d, z location = %d, s location = %d"
    ^                      ^                ^                ^
    |           %d requires that the argument is int. None of str, z, &s is int
    %s requires that the argument is char*. s is a std::string instead

使用std::cout表示字符串没有变化会更方便:

char str[] = "Test test";
string s(str);
std::cout << s << '\n'; // prints Test test
str[0] = 'n';
std::cout << s << '\n'; // prints Test test

【讨论】:

  • 感谢您的回答。似乎问题是由我的编译器(DEV C++)引起的,因为当我计算字符串时,字符串的第一个字母发生了变化。 :(
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-25
  • 2012-11-04
  • 1970-01-01
  • 2019-08-04
  • 2011-03-22
  • 1970-01-01
相关资源
最近更新 更多