4.3 复制数组

Posted: March 25, 2011 in C++

Strcpy

/*strcpy()将整个字符串复制到指定的缓冲区中, 但是如果源数组比目标数组长, strcpy()将覆盖缓冲区后面的内容
语法:strcpy(被复制的数组,复制的数组);
使用strcpy需要使用string头文件*/

#include <iostream>
#include <string>

using namespace std;

void main()
{
            char string1[100];
            char string2[100];

            cout<<“Enter string 1:“;
            cin.get(string1,99);

            strcpy(string2,string1);//复制string1到string2.

            cout<<“string1–>copy–>”<<endl<<“string2:”<<string2<<endl;
}

Strncpy

/*strncpy()将第一个空字符前的内容或指定的最大字符数复制到目标缓冲区中.string+number+copy
语法:strncpy(string2,string1,number);*/

#include <iostream>
#include <string>

using namespace std;

void main()
{
            char string1[100];
            char string2[100];

            cout<<“string1:”;
            cin.get(string1,99);//最大字符为99,剩余1是空字符存入数组中.
            cout<<“string1–>copy”<<endl;

            strncpy(string2,string1,99);
            cout<<“string2:”<<string2<<endl;

}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s