【问题标题】:Concat Program, Weird symbolsConcat 程序,奇怪的符号
【发布时间】:2015-06-17 08:44:26
【问题描述】:

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

【问题讨论】:

  • 我猜“傻瓜”一书没有告诉你 C 风格字符串函数的正确 #include 是 &lt;cstring&gt;,而不是 &lt;string&gt;。此外,您的代码在某些方面存在缺陷,所有这些缺陷都可以通过 not 使用 char 数组,而是使用 std::string 来清除。

标签: c++ concatenation


【解决方案1】:

问题就在这里:

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

字符文字应该是'\0'。该符号是一个反斜杠,后跟一到三个八进制数字:它创建一个具有编码值的字符。 char(0) == \0 是用于分隔“C 样式”即 ASCIIZ 字符串的 ASCII NUL 字符。

这实际上允许观察到的输出(并注意行为是未定义的,您可能无法始终看到该输出)的方式是......

concatString(szString1, " - ");

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

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

【讨论】:

  • 它会在项目/编译器或 buld 设置中的某个位置,或者被 google 快速找到。
猜你喜欢
  • 2013-08-16
  • 2017-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-25
  • 2011-01-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多