【问题标题】:C++ char to string acting funky [closed]C ++ char到字符串表现时髦[关闭]
【发布时间】:2016-12-12 08:46:12
【问题描述】:

这是代码:

int main(){

 string word= "word";

char ciphered[word.length()];

for(int i=0; i<word.length(); i++)
{
int current_position = (int) word[i];
int new_position = current_position + 2;
char this_char = (char) new_position;
ciphered[i] = this_char;

}



string str(ciphered);

cout << str << endl ;

}

当我运行它时,它会打印:

但是当我这样做时:

   for(int i = 0; i<sizeof(ciphered); i++)
   {
    cout << ciphered[i] << endl ;
   }

它打印出同样的东西,但没有最后三个标志,这是正确的 但是每当我尝试将此字符数组转换为字符串时,它会添加最后三个奇怪的符号,我不知道为什么

【问题讨论】:

  • @Kon 与c 相同:标记垃圾邮件。不过,公平地说,它实际上也不是 c++。请参阅 VLA。
  • 您可能只想通过适当的编译器运行它。注意:您也不必通过 Java 和/或 C 编译器运行 C++ 代码。现代 C++ 编译器直接生成二进制文件。
  • 不要发布文字图片!
  • 在 C++ 中,字符串以 null (char 0) 结束。您的循环可能会覆盖字符串终止符,因此您会看到一些垃圾字符正在影响未初始化的内存。使用sizeof() 可以通过对打印的字符数设置数字限制来避免这种情况。
  • 我懒得用mingw编译器

标签: c++


【解决方案1】:

首先,这个:

char ciphered[word.length()];

不是合法的 C++ 代码,尽管 gcc 可以接受它。但第二点,您并不需要真正的 char 数组,因为您可以使用 std::string 本身访问单个符号:

string word= "word";
string ciphered( word.length(), ' ' );

for(int i=0; i<word.length(); i++)
{
    ciphered[i] = word[i] + 2;
}
cout << ciphered << endl;

您的代码会打印额外的符号,因为您没有在 C 样式字符串上放置空终止符并通过 std::ostream 发送它,这会导致 UB 并打印在您的 char 数组之后发生在内存中的垃圾,直到它突然找到空终止符或崩溃因为访问了无效的内存。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-02
    • 2020-10-16
    • 2017-05-03
    相关资源
    最近更新 更多