Concat 程序,奇怪的符号

Concat Program, Weird symbols

我正在关注有关连接字符串的 'C++ for Dummies' 部分。然而,我下面的程序输出了两个串联的字符串,但中间有一大堆奇怪的符号。

#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <string>

using namespace std;

void concatString(char szTarget[], const char szSource[]);

int main()
{
    //read first string
    char szString1[128];
    cout << "Enter string #1";
    cin.getline(szString1, 128);

    //second string
    char szString2[128];
    cout << "Enter string #2";
    cin.getline(szString2, 128);

    //concat - onto first
    concatString(szString1, " - ");

    //concat source onto target
    concatString(szString1, szString2);

    //display
    cout << "\n" << szString1 << endl;
    system("PAUSE");
    return 0;
}

//concat source string onto the end of the target string

void concatString(char szTarget[], const char szSource[])
{
    //find end of the target string
    int targetIndex = 0;
    while(szTarget[targetIndex])
    {
        targetIndex++;
    }

    //attach the source string onto the end of the first
    int sourceIndex = 0;

    while(szSource[sourceIndex])
    {
        szTarget[targetIndex] = szSource[sourceIndex];
        targetIndex++;
        sourceIndex++;
    }

    //attach terminating null
    szTarget[targetIndex] = '/0';
}

输出显示为

输入字符串#1hello 输入字符串 #2world

你好 - 0╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠ ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠ ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠ ╠╠Óu¬ñ°'world0 按任意键继续 。 . .

问题在这里:

//attach terminating null
szTarget[targetIndex] = '/0';

字符文字应为 '[=12=]'。该符号是一个反斜杠后跟一到三个八进制数字:创建一个具有编码值的字符。 char(0) == [=14=] 是用于分隔 "C-style" aka ASCIIZ 字符串的 ASCII NUL 字符。

这实际上允许观察到的输出的方式(请注意行为未定义,您可能看不到一致的输出)是...

concatString(szString1, " - ");

...留下 szString1 包含 hello - 后跟 '/0' 这是一个无效的字符文字,但似乎已被编译器视为 '0',然后被任何其他垃圾恰好在分配 szString1 的堆栈中。下一个 concatString 调用将尝试在向内存附加 "world" 之前找到该内存中的第一个 NUL,而 "first NUL" 显然在 0╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠ ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠Óu¬ñ° 之后。然后带有那个和 world 的缓冲区本身后面跟着 0 并且仍然没有终止。当您最终调用 cout << "\n" << szString1 << endl; 时,它会输出所有这些内容以及它发现的任何其他垃圾,直到它遇到 NUL,但从输出来看,它看起来像是在 world0.

之后立即发生的

(我很惊讶你的编译器没有警告无效的字符文字:你启用了所有可能的警告吗?)