gpt4 book ai didi

c - 如何通过更改数据类型在不同变量中获取没有空格的输入

转载 作者:太空宇宙 更新时间:2023-11-04 04:11:39 24 4
gpt4 key购买 nike

通过使用给定的源代码,我正在尝试进行一些算术运算。给定的输入是:

1
234*34

由于 234* 以及 34 之间没有空格,scanf 无法正确读取它。我应该怎么做才能让 scanf 读取此输入并给出正确答案而不在输入数字之间提供空格?

#include <stdio.h>
int arithematic(){
int a,c,t,i=0,k,l;
char b[100];
scanf("%d%s%d",&a,&b[0],&c);
if(b[0] =='+')
t = a+c;
if(b[0] == '-')
t=a-c;
if(b[0]=='*')
t=a*c;
k=a;
l=c;
while(k>0||l>0)
{
k/=10;l/=10;
i++;
}

printf("%d\n",a);
printf("%s",b);
printf("%d\n",c);

while(i>0)
{
printf("-");
i--;
}

printf("\n%d\n",t);
}

int main(void)
{
int n;

scanf("%d",&n);
while(n--)
{
arithematic();
printf("\n");
}
}

最佳答案

scanf("%d%s%d",&a,&b[0],&c); 替换为 scanf("%d %1[+-*/]% d",&a,b,&c);%1[+-*/] 的含义是恰好消耗属于四个运算符集合的一个字符。它前面的空格用于占用可选的空格。

关于c - 如何通过更改数据类型在不同变量中获取没有空格的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56610137/

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