读书人

关于std:endl;解决方法

发布时间: 2012-04-12 15:46:35 作者: rapoo

关于std::endl;
代码能通过编译。
#include <iostream>
#include <string>
#include <cstring>

using namespace std;

int main(){
char *cp = "hello world!";
char *cp2 = "Hello World!!";

size_t slength = strlen(cp);
size_t slength2 = strlen(cp2);
const size_t arr_size = slength + slength2 + 1;
//cout << endl;

char arr[arr_size];
strncpy(arr,cp,slength);
strncat(arr,cp2,slength2+1);

string str ("Hello world!!!");
string str2("Hello World!!!!");
string str3;

str3 = str + str2;

cout << arr <<endl <<str3 <<endl;

system("pause");
return 0;
}

运行结果:
hello world!Hello World!!
Hello world!!!Hello World!!!!
为什么出现乱码了。
而把代码中注释掉的语句,去掉注释程序运行结果为:

hello world!Hello World!!
Hello world!!!Hello World!!!!

谁可以给说说什么原因啊!谢谢!!

[解决办法]
strncpy(arr,cp,slength);

改成
strncpy(arr,cp,slength+1);
[解决办法]

探讨

char arr[arr_size]; //这个真能通过编译?arr_size在程序运行时才确定值···

[解决办法]
我很好奇楼主是什么编译器,怎么编译通过的。
strlen()应该是个函数,所以在执行的时候才能知道字符串的长度。
char arr[arr_size];//这句话应该是在编译的时候就需要确定arr_size的大小了。
在编译的时候编译器不知道arr_size的大小,怎么通过呢?

读书人网 >C++

热点推荐