gpt4 book ai didi

c++ - Concat 程序,奇怪的符号

转载 作者:行者123 更新时间:2023-11-28 06:12:55 24 4
gpt4 key购买 nike

我正在关注“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';

字 rune 字应为 '\0' .该符号是一个反斜杠后跟一到三个八进制数字:创建一个具有编码值的字符。 char(0) == \0是用于分隔“C 风格”又名 ASCIIZ 字符串的 ASCII NUL 字符。

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

concatString(szString1, " - ");

...叶子 szString1包含 hello -后跟'/0',这是一个无效的字 rune 字,但似乎已被您的编译器视为'0',然后是szString1 所在堆栈中碰巧出现的任何其他垃圾。被分配了。下一个concatString调用将在追加 "world" 之前尝试在该内存中找到第一个 NUL。到它,并且“第一个 NUL” 显然在 0╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠ ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠Óu¬ñ° 之后.然后缓冲区和 world本身后面跟着 0仍然没有终止。当你终于拨通cout << "\n" << szString1 << endl;它输出所有这些以及它发现的任何其他垃圾,直到它遇到 NUL,但从输出来看,它看起来像是在 world0 之后立即发生的。 .

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

关于c++ - Concat 程序,奇怪的符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30886538/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com