gpt4 book ai didi

c - 无效的初始值设定项 : strcat(s, str);在C程序中

转载 作者:行者123 更新时间:2023-11-30 19:05:03 25 4
gpt4 key购买 nike

我正在 hackerrank 中编写程序,并尝试使用 strcat() 函数连接两个字符串,但它对我不起作用。

我是学生,正在学习 C 语言,你能帮我找到连接两个字符串的方法吗?

这是我的代码:

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

int main() {
int i = 4;
double d = 4.0;
char s[] = "HackerRank ";

// Declare second integer, double, and String variables.
int j;
double e;
char str[] = "";

// Read and save an integer, double, and String to your variables.
scanf("Enter integer : %d",&j);
scanf("Enter double : %lf",&e);
scanf("Enter string : %s",str);

// Print the sum of both integer variables on a new line.
int sum = i + j;
printf("\n %d",sum);

// Print the sum of the double variables on a new line.
double doubleSum = d + e;
printf("\n %lf",doubleSum);

// Concatenate and print the String variables on a new line
char finalString[] = strcat(s,str);
printf("%s",finalString);

// The 's' variable above should be printed first.
return 0;
}

错误:

solution.c: In function ‘main’:
solution.c:30:26: error: invalid initializer
char finalString[] = strcat(s,str);
^~~~~~

Compiler Error

最佳答案

检查下面的代码:

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

int main() {
int i = 4;
double d = 4.0;
char s[] = "HackerRank ";
char *finalString = NULL;
int j;
double e;
char str[100];
scanf("%d",&j);
scanf("%lf",&e);
scanf("%s", &str);
int sum = i + j;
printf("\n %d",sum);
double doubleSum = d + e;
printf("\n %lf",doubleSum);
finalString = realloc(finalString, strlen(s) + strlen(str) + sizeof(char));
strcat(finalString,s);
printf("\n %s",finalString);
strcat(finalString,str);
printf("\n %s \n",finalString);
return 0;
}

关于c - 无效的初始值设定项 : strcat(s, str);在C程序中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50706456/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com