gpt4 book ai didi

c 获取下一个不带空格的字符

转载 作者:行者123 更新时间:2023-11-30 20:39:40 24 4
gpt4 key购买 nike

我需要以下代码的帮助。程序进行简单的算术计算。问题是 2(space)+3 工作正常,但 2+3 不读取运算符。我怎样才能让它在没有空间的情况下工作?getchar 和 putchar 是必须的,没有字符串函数。该程序的作用是提取2个操作数和运算符,进行指定的计算并显示结果。提前致谢。

while ((ch = getchar()) != EOF)  /*Begining of the while loop*/
{
if ((status == first)) {
if ((ch >= '0') && (ch <= '9'))
{
num1 = ((num1 * 10) + (ch - '0'));
}
else status = operand;
}
else if (status == operand)
{
if (ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '%'){
/*count++;*/
oper = ch;
/*printf("Count %d \n", count);
}
else if (count>1){ // This opening brace was missing
printf("Operator Error.\n");*/
status = second;
}
}
else if ((status == second) && ((ch >= '0') && (ch <= '9'))){
num2 = ((num2 * 10) + (ch - '0'));
}
}

最佳答案

这会忽略状态变量并检查是否已分配操作数以确定这些数字是否用于 num1 或 num2。非数字在 else 中被消耗,如果它们是有效的操作数,则分配操作数。输入在 EOF 或 '\n' 处停止

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

int main() {
int num1 = 0;
int num2 = 0;
int ch = 0;
char operand = 0;

while (((ch = getchar()) != EOF) && ch != '\n') {
if ((ch >= '0') && (ch <= '9')) { // digits
if (operand == 0) {
num1 = ((num1 * 10) + (ch - '0')); // no operand so use num1
}
else {
num2 = ((num2 * 10) + (ch - '0')); // operand has been assigned
}
}
else { // non digits
if (ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '%'){
if ( operand == 0) { // do not re-assign operand
operand = ch; // assign operand
}
}
}
}
printf ( "num1 %d operand %c num2 %d\n", num1, operand, num2);
return 0;
}

这也可以代替上面的 while 循环
%d 读取一个整数
%1[-+/*%] 读取必须是有效操作数之一的单个字符。 %1 之前的空格会跳过任何空格(如果存在)
%d 读取另一个整数
如果 scanf 成功读取这三个值,则会打印它们。

char operand[2] = {0};
if ( ( scanf ( "%d %1[-+/*%] %d", &num1, operand, &num2)) == 3) {
printf ( "num1 %d operand %c num2 %d\n", num1, operand[0], num2);
}

关于c 获取下一个不带空格的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26335923/

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