【发布时间】: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 是
<cstring>,而不是<string>。此外,您的代码在某些方面存在缺陷,所有这些缺陷都可以通过 not 使用 char 数组,而是使用std::string来清除。
标签: c++ concatenation