康卡特程序,奇怪的符号

Concat Program, Weird symbols

本文关键字:符号 程序 康卡特      更新时间:2023-10-16

我正在遵循"傻瓜C++"部分关于连接字符串。但是,我下面的程序输出连接的两个字符串,但中间有很多奇怪的符号。

#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';

字符文字应'' 。 表示法是一个反斜杠,后跟一到三个八进制数字:它创建一个具有编码值的字符。 char(0) == 是 ASCII NUL 字符,用于分隔"C 样式"(又名 ASCIIZ 字符串)。

这实际上允许观察到的输出(请注意,行为是未定义的,您可能不会始终如一地看到该输出)是......

concatString(szString1, " - ");

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

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