简体   繁体   English

如何将一个char中的值分配给一个指针?

[英]How to assign value from a char into a pointer?

In function input, I was trying to do an input validation that will only accept input from the given choices. 在函数输入中,我试图进行输入验证,该输入验证将仅接受来自给定选择的输入。 I tried using only the variable opt to get the values from scanf but when I compare with if, it gives an error saying something about comparing a pointer to another type. 我尝试仅使用变量opt从scanf获取值,但是当我与if进行比较时,它给出了一个错误,该错误说明了将指针与另一种类型进行比较。

With this code, I kinda managed to make that error disappear and the program now runs but the program ends after I input the choice. 使用此代码,我设法使该错误消失,并且程序现在可以运行,但是在输入选择后程序结束了。 Can anyone help me with this? 谁能帮我这个? Thanks :) 谢谢 :)

#include <stdio.h>
#include <ctype.h>

int add(int n1, int n2);
int subtract(int n1, int n2);
int multiply(int n1, int n2);
int divide(int n1, int n2);
void input(int *n1, int *n2, char *opt);


int main(void)
{
    int n1, n2, ret;
    char opt;

    start:
    input(&n1, &n2, &opt);

    switch(opt)
{
            case '1': 
                ret = add(n1, n2);
                printf("The sum is %d\n", ret);
                break;
            case '2':
                ret = subtract(n1, n2);
                printf("The difference is %d\n", ret);
                break;
            case '3': 
                ret = multiply(n1, n2);
                printf("The product is %d\n", ret); 
                break;              
            case '4': 
                ret = divide(n1, n2);
                printf("The quotient is %d\n", ret);
                break;
            case 'R':
                goto start;
                break;
            case 'E':
                printf("Goodbye!\n");
                return 0;
                break;
    }
    return 0;   
}


void input(int *n1, int *n2, char *opt)
{
    int valid;
    char choice;

    printf("Enter first number: \n");
    scanf("%d", n1);

    printf("Enter second number: \n");
    scanf("%d", n2);   

    getchar();
    valid = 0;
    while( valid == 0)
    {
        printf("Addition -> 1\nSubtraction -> 2\nMultiplication -> 3\nDivision -> 4\nReset -> R\nExit -> E\n");


        if ( scanf("%c", &choice) == ('1' || '2' || '3' || '4' || 'R' || 'E'))
        {
            valid = 1;
        }
        else
        {
            printf("Invalid input!\n");
        }
    }
    opt = &choice;

}


int add(n1, n2)
{
    int result;
    result = (n1+n2);
    return result;
}

int subtract(n1, n2)
{
    int result;
    result = (n1-n2);
    return result;
}

int divide(n1, n2)
{
    int result;
    result = (n1/n2);
    return result;
}

multiply(n1, n2)
{
    int result;
    result = (n1*n2);
    return result;
}

One of the problems with the program you show is that it will not give you the option entered. 一个与你展示程序的问题是,它不会给你输入的选项。 That's because arguments are passed by value in C, which means that arguments are copied and changing an argument will not change the original value. 这是因为参数在C中按值传递,这意味着将复制参数,并且更改参数不会更改原始值。

This is noticeable when you do 当您这样做时,这很明显

opt = &choice;

This reassignment of the opt pointer will be lost once the function returns. 函数返回后,对opt指针的重新分配将丢失。

What you want in this specific case is to use the dereference operator to dereference the pointer you pass in, and assign the value of choice to the dereferenced pointer: 在这种特定情况下,您想要的是使用取消引用运算符取消引用传入的指针,并将choice值分配给取消引用的指针:

*opt = choice;

There are many other errors in your code, including one which you don't notice because it works but not in the way you expect it to. 您的代码中还有许多其他错误,包括您不会注意到的一个错误,因为它可以正常工作,但并非您期望的那样。

Lets take the condition 让条件

scanf("%c", &choice) == ('1' || '2' || '3' || '4' || 'R' || 'E')

The scanf function returns the number of successfully parsed formats, or EOF . scanf函数返回成功解析的格式数,即EOF In your case it would return 1 if it read and parsed a character. 在您的情况下,如果读取并解析了一个字符,它将返回1

The expression ('1' || '2' || '3' || '4' || 'R' || 'E') is the one that doesn't work as expected. 表达式('1' || '2' || '3' || '4' || 'R' || 'E')是无法正常工作的表达式。 In C all non-zero values are considered "true", only zero is "false". 在C语言中,所有非零值均视为“ true”,只有零为“ false”。 If your system is using the ASCII alphabet (most likely) then the expression 如果您的系统使用的是ASCII字母 (最有可能),则表达式

('1' || '2' || '3' || '4' || 'R' || 'E')

is equivalent to 相当于

(49 || 50 || 51 || 52 || 82 || 69)

All of the sub-expressions are "true" leading to the while expression to be "true" which in C is equivalent to 1 . 所有子表达式均为“ true”,导致while表达式为“ true”,在C中等于1

So the expression 所以表达

scanf("%c", &choice) == ('1' || '2' || '3' || '4' || 'R' || 'E')

is equivalent to 相当于

scanf("%c", &choice) == 1

which is what you should check for, but not in this way. 这是您应该检查的内容,但不是这种方式。

What you should do is to put a check inside the loop for the correct alternative, but remember what I said the result of ('1' || '2' || '3' || '4' || 'R' || 'E') would be. 您应该做的是将检查放入循环中以查找正确的替代方法,但请记住我所说的('1' || '2' || '3' || '4' || 'R' || 'E')将。

I think the above answer explains why your code doesn't work very well, so here is a working version of your input() function and a bit shorter version of the operator functions: 我认为上面的答案解释了为什么您的代码不能很好地工作的原因,因此这是input()函数的有效版本和运算符的简短版本:

void input(int *n1, int *n2, char *opt)
{
    int valid;
    char choice = '0';

    printf("Enter first number: \n");
    scanf("%d", n1);

    printf("Enter second number: \n");
    scanf("%d", n2);   

    getchar();
    valid = 0;
    while( valid == 0)
    {
        printf("Addition -> 1\nSubtraction -> 2\nMultiplication -> 3\nDivision -> 4\nReset -> R\nExit -> E\n");

        choice = getchar();
        switch (choice) {
            case ('1', '2', '3', '4', 'R', 'E'):
                valid = 1;
                break;
            default: printf("Invalid input!\n");
                break;
        }
    }
    *opt = choice;
}

and the operators you can just do 和你可以做的操作员

int add(n1, n2)
{
    return n1 + n2;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM