strcpy()函数用来拷贝字符串。
示例
//Visual Studio中加上这句才可以使用scanf()
//否则只能使用scanf_s()
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdbool.h>
//引入字符串函数string.h
//一些ANSI之前的系统使用strings.h头文件,而
//有些系统可能根本没有字符串头文件。
#include <string.h>
#define SIZE 40
#define LIM 5
char * s_gets(char * st, int n);
//argc: 参数个数 argv[]: 参数数组
int main(int argc, char *argv[])
{
char qwords[LIM][SIZE];
char temp[SIZE];
int i = 0;
printf("Enter %d words beginning with q:\n", LIM);
while (i < LIM && s_gets(temp, SIZE))
{
//if (strncmp(temp, "q", 1) != 0)
if (temp[0] != 'q')
printf("%s doesn't begin with q!\n", temp);
else
{
strcpy(qwords[i], temp);
i++;
}
}
puts("Here are the words accepted:");
for (i = 0; i < LIM; i++)
puts(qwords[i]);
//char target[20];
//int x;
//x = 50; //数字赋值
//strcpy(target, "Hi ho!"); //字符串赋值
//target = "So long"; //语法错误
//char * str;
//有问题,str未初始化,该字符串可能被拷贝到任意地方
//strcpy(str, "The C of Tranquility");
system("pause");
return 0;
}
char * s_gets(char * st, int n)
{
char * ret_val;
int i = 0;
ret_val = fgets(st, n, stdin);
if (ret_val) //即,ret_val != NULL
{
while (st[i] != '\n' && st[i] != '\0')
i++;
if (st[i] == '\n')
st[i] = '\0';
else
while (getchar() != '\n')
continue;
}
return ret_val;
}
示例:strcpy()的返回值
//Visual Studio中加上这句才可以使用scanf()
//否则只能使用scanf_s()
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdbool.h>
//引入字符串函数string.h
//一些ANSI之前的系统使用strings.h头文件,而
//有些系统可能根本没有字符串头文件。
#include <string.h>
#define SIZE 40
#define WORDS "beast"
//argc: 参数个数 argv[]: 参数数组
int main(int argc, char *argv[])
{
const char * orig = WORDS;
char copy[SIZE] = "Be the best that you can be.";
char * ps;
puts(orig);
puts(copy);
//将orig拷贝到copy的第7个位置并覆盖之后的字符
//ps指向copy的7个索引
ps = strcpy(copy + 7, orig);
puts(copy);
puts(ps);
system("pause");
return 0;
}