gpt4 book ai didi

在c中连接字符数组(字符串)

转载 作者:太空宇宙 更新时间:2023-11-04 08:49:13 26 4
gpt4 key购买 nike

在我的程序中,用户输入这样的行 (5*(22+1))。现在我需要将数字和其他字符分开。所以我写了这样的代码。在c中可以这样做吗?或者有什么简单的方法可以解决这个问题吗?我试试这个方法。

#include <stdio.h>
int main()
{
int i=0;
char s[50];
printf("Enter the line");
gets(s);

while(s[i]!='\n')
{
if(s[i]=='+' || s[i]=='-',s[i]=='*',s[i]=='/')
{
break;
}
else
{
char n[5];
n=n+s[i];
}
printf("%s",n);

i++;

}


return 0;
}

最佳答案

我建议你看看sscanf功能。它可能有助于提取小数。

另外,你的代码错误比较多:

if(s[i]=='+' || s[i]=='-',s[i]=='*',s[i]=='/')

应该是

if(s[i]=='+' || s[i]=='-' || s[i]=='*' || s[i]=='/')


char n[5];
n=n+s[i];

这是错误的。 n 是一个指针(内存地址)。向它添加一个字符是没有意义的。如果您想进行串联,请查看 strcat功能。另请注意,您没有初始化 n。在 C 中,这是必需的。

printf("%s",n);

这里 n 超出了范围。它就存在于大括号之间:

{
char n[5];
n=n+s[i];
} //here n does not exists any more

为防止这种情况,声明 n 个外括号。

关于在c中连接字符数组(字符串),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20274179/

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