gpt4 book ai didi

c - 为什么我没有得到连接的字符串?

转载 作者:行者123 更新时间:2023-12-05 01:40:38 24 4
gpt4 key购买 nike

我写了这段代码,我想添加两个整数、两个 double 并连接两个字符串,其中一个整数、 double 和字符串已经声明,另一个整数、字符串和 double 将由用户。但似乎该程序没有将另一个字符串作为输入。

我写了一个类似的程序,我可以使用 scanf 从用户那里获取字符串,但同样的方法在这里不起作用。

int main() {
int i = 4;
double d = 4.0;
char s[] = "My college name is ";

// Declare second integer, double, and String variables.
int i2,sum1;
double d2,sum2;
char s2[100];

// Read and save an integer, double, and String to your variables.
scanf("%d",&i2);
scanf("%lf",&d2);
scanf("%[^\n]%*c",&s2);

sum1= i+i2;
sum2= d+d2;
strcat(s,s2);

// Print the sum of both integer variables on a new line.
printf("%d\n",sum1);
printf("%.1lf\n",sum2);
printf("%s",s);


return 0;}

在我进行必要的更改后,例如从 s2 中删除 & 并将 s[] 更改为 s[200],我仍然无法获得连接的字符串。我正在编写我编辑过的代码。请帮助我。

int main() {
int i = 4;
double d = 4.0;
char s[200] = "My college name is ";


// Declare second integer, double, and String variables.
int i2,sum1;
double d2,sum2;
char s2[100];

// Read and save an integer, double, and String to your variables.
scanf("%d",&i2);
scanf("%lf",&d2);
scanf("% [^\n]%*c",s2);

sum1= i+i2;
sum2= d+d2;
strcat(s,s2);

// Print the sum of both integer variables on a new line.
printf("%d\n",sum1);
printf("%.1lf\n",sum2);
printf("%s",s);


return 0;
}

请帮我解决这里的错误。

最佳答案

它不接受您的字符串输入,因为您使用 %[^\n]%*c 扫描字符串。它指示程序在得到一个换行符作为输入 后返回。并且字符串在扫描d2后从缓冲区中得到一个换行符,并返回而不进行进一步的输入。

要摆脱这种情况,您需要在输入字符串之前输入一个字符。更改以下行:

scanf("%lf",&d2);
scanf("%[^\n]%*c",&s2);

收件人:

scanf("%lf",&d2);
getchar();
scanf("%[^\n]%*c",&s2);

并且您的代码将正确地接受字符串输入。

此外,您还可以通过在 之前放置一个额外的 空格 来做到这一点(在输入字符串之前输入额外的字符) % 符号。

更改以下行:

scanf("%[^\n]%*c",&s2);

收件人:

scanf(" %[^\n]%*c",&s2);

也做同样的事情。

关于c - 为什么我没有得到连接的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56119341/

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