否则字符逻辑有缺陷

if else character logic is flawed

本文关键字:有缺陷 字符      更新时间:2023-10-16

好的,所以我现在尝试使用下面的函数检查代码 check_status()。

它们在代码中没有错误,但我认为我搞砸了逻辑。当它运行时,我想做的是放入 S 并让它打印"正确答案。S"

现在代码工作正常,当您输入 FEFWRGV 或不是 S、SH、MJ、MS 的内容时,会打印出错误消息。然而!当你输入SSDFIEWF或类似的东西时,它会说"正确答案。S"

我检查是否输入了 S 的方法是if (状态[0] == 'S')

有没有办法编写这样的代码:if (status[0] == 'S' && status[1] == void)

因为我知道我正在做的是检查状态[0],然后我想确保状态[1]没有被使用。

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <cstdio>
//functions called
float wages_loop();
float other_loop();
float interest_loop();
void check_status();

//start main 
int main(void)
{
    char status[10], another[10];
    char buffer[80];
    float wages, other_income, interest, dividends, test;
    int dependents;
    int single_acc = 0, mj_acc = 0, ms_acc = 0, sh_acc = 0;
    printf("Would you like to start: ");
    gets_s(another);
    if (another[0] != 'y' && another[0] != 'n')
    {
        while (another[0] != 'y' && another[0] != 'n')
        {
            printf("nn INCORRCT ANSWER. nn");
            printf("n Would you like to start. (y or n)");
            gets_s(another);
        }
    }
    while (another[0] == 'y')
    {

        check_status();

        interest = 0;

        printf("nntt Your interest is: %.2f n", interest);
        system("pause");
        printf("Would you like anoter: ");
        gets_s(another);
        if (another[0] != 'y' && another[0] != 'n')
        {
            while (another[0] != 'y' && another[0] != 'n')
            {
                printf("nn INCORRCT ANSWER. nn");
                printf("n Would you like anoter. (y or n)");
                gets_s(another);
            }
        }
    } //end loop
    printf("nnttt Number of Singles filleing: %i n", single_acc);
    return 0;
}//end main

void check_status()
{
    char status[10];
    int check = 0;
    while (check != 1)
    {
        printf("What is your Status: ");
        gets_s(status);
        if (status[0] == 'S' && status[1] == 'H')
        {
            printf("nn CORRECT ANSWER. SH nn");
            check = 1;
        }
        else if (status[0] == 'S')
        {
            printf("nn CORRECT  ANSWER. S nn");
            check = 1;
        }
        else if (status[0] == 'M' && status[1] == 'J')
        {
            printf("nn CORRECT ANSWER. MJ nn");
            check = 1;
        }
        else if (status[0] == 'M' && status[1] == 'S')
        {
            printf("nn CORRECT ANSWER. MS nn");
            check = 1;
        }
        else
        {
            printf("nn INCORRECT ANSWER. noting nn");
        }
    }   
}

有没有办法我可以编写这样的代码:if (status[0] == 'S' && status1 == void)

你快到了。C-"字符串"终止不是void而是''

因此,要测试"字符串"是否在第 1个字符之后结束,即status[0]执行以下操作:

if (status[0] == 'S' && status[1] == '') 

顺便说一句:要声明一个没有任何参数的函数,请使用void,如下所示:

check_status(void);

正如Joachim Pileborg已经评论过你的问题,你用错了gets_s()gets_s()采用两个参数。

编译器应该警告您缺少第二个参数。

认真对待此类警告是个好主意。