将变量在C中合并为1 [关闭]

问题描述 投票:-4回答:1

我目前正在学习C,希望为我的程序连接字符串变量-有问题的代码行是:

char full_name = first_name[50] + second_name;

正如我说的,我正在尝试将2个字符串变量连接为1个变量,然后在另一个称为的函数中显示%s(是的-我已经在本教程系列中寻求帮助我正在追踪以及在互联网上的其他地方)。

应要求在这里是我的代码:

#include <stdio.h>

包括

int main()
{
    char first_name[50];
    char second_name[50];
    char full_name[50] = first_name + second_name;
    function1();
    function2();
    function3();


    return 0;
}

void function1()
{
    char first_name[50];
    char second_name[50];
    char full_name[50] = first_name, second_name;
    printf("Enter your first name: \n");
    fgets(first_name, 50, stdin);
}

void function2()
{
    char first_name[50];
    char second_name[50];
    char full_name[50] = first_name, second_name;
    printf("Enter your second name: \n");
    fgets(second_name, 50, stdin);
}

void function3()
{
    char first_name[50];
    char second_name[50];
    char full_name = first_name, second_name;
    printf("Your name is: \n %s ", full_name);

}

任何帮助将不胜感激,

凯洛格的32

c
1个回答
0
投票

C字符串是多变的,为了更好地使用它们,您必须了解它们的工作方式。

C中的字符串被实现为char s的数组。字符串函数用来访问和操作字符串的值是指向字符串中第一个字符的指针。

例如:

char string[]={'h','e','l','l','o','\0'};创建一个以'\0'结尾的字符数组,这是一个空终止符,告诉字符串函数停止读取。如果在字符串的末尾找不到此字符,则会发生坏的坏事情。

C标准不会为您做任何花哨的幕后操作,因此,如果要串联两个字符串,则必须手动为新的串联字符串腾出空间,并将数据复制到其中。

看看下面的例子:

#include <stdio.h>
#include <string.h>

char first_name[] = "Jane";
char second_name[] = "Doe";

int firstLen=strlen(first_name); //firstLen should be 4
int secondLen=strlen(second_name); //secondLen should be 3

char full_name[firstLen+secondLen+1]; //Room for both strings and a null-terminator
strcpy(full_name,first_name); //Copy first_name into full_name
strcpy(&full_name[firstLen],second_name); //Copy second_name into spot right after first_name

在此代码中,first_name和second_name将指向自动以空值终止的只读C字符串。

strlen(),C标准的字符串长度函数返回char的数量之前且不包括空终止符。

[strcpy(char *destination,char *source)是C-标准字符串复制功能,但是在调用它之前,必须确保在destination处有足够的空间容纳该字符串。

此代码完成后,如果运行printf("%s\n",full_name);,则应以JaneDoe作为输出。

如果您想在名称之间留一个空格,则必须像这样手动为其留出空间:

char full_name[firstLen+secondLen+2]; //Room for both strings, a space, and a null-terminator
strcpy(full_name,first_name); //Copy first_name into full_name
full_name[firstLen]=' '; //Save a space right after the first name
strcpy(&full_name[firstLen+1],second_name); //Copy second_name into spot right after space

那么您可以期待输出Jane Doe

我知道这对于不习惯C的编码人员来说是超级困惑,但是我敢肯定,您会掌握它的。

祝你好运!

© www.soinside.com 2019 - 2024. All rights reserved.