Concat程序,奇怪的符号

时间:2015-06-17 08:44:27

标签: c++ concatenation

我正在关注连接字符串的'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 按任意键继续 。 。

1 个答案:

答案 0 :(得分:1)

问题出在这里:

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

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

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

concatString(szString1, " - ");

...离开szString1包含hello -后跟'/ 0'这是一个无效的字符文字,但似乎被编译器视为'0',然后被其他任何垃圾视为碰巧是在分配了szString1的堆栈中。下一个concatString调用将尝试在向"world"追加0╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠ ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠Óu¬ñ°之前找到该内存中的第一个NUL,并且world之后明显“第一个NUL”。然后缓冲区和0本身后跟cout << "\n" << szString1 << endl;,仍然没有终止。当你最后调用world0时,它会输出所有这些以及它找到的任何其他垃圾,直到它到达NUL,但是从输出看起来就像在sresult = sresult.Replace("""", String.Empty) If sresult.Contains("Status:Accepted") Then Dim parts = sresult.Replace("{", String.Empty).Replace("}", String.Empty).Split(",") For i As Int16 = 0 To parts.Length - 1 If parts(i).StartsWith("Detail") Then (yourclass).RedirectURL = parts(i).Substring(7) End If If parts(i).StartsWith("Price") Then (yourclass).LenderComm = CDec(parts(i).Substring(6)) End If 之后发生的那样。

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

相关问题