c - 我的 scanf 函数在 if 函数内部不起作用

标签 c

当我在输入“a”或“b”后尝试在 if 函数内部运行 scanf 时,它会立即运行并退出程序而不获取输入。有没有办法修复它,以便 scanf 在 if 和 else if 函数内部工作?

#include <stdio.h>
#include <string.h>

int top=-1;
int word;


char stack_string[100];
void push(char word);
char pop(void);
int main()
{
    char input;
    char str[100];
    int i;
    printf("press [a] for palindrome check, [b] for string reversal:");
    scanf("%c", &input);

    if (input == 'b'){
        printf("Input a string: ");
        scanf("%[^\n]s", str);
        for(i=0;i<strlen(str);i++)
            push(str[i]);
        for(i=0;i<strlen(str);i++)
            str[i]=pop();
        printf("Reversed String is: %s\n",str);
    }
    else if(input == 'a'){
        char str[100];
        int count = 0;
        printf("Input a string: ");
        scanf("%[^\n]s", str);

        for (i = 0; i < strlen(str); i++)
        {
            push(str[i]);
        }

        for (i = 0; i < strlen(str); i++)
        {
            if (str[i]==pop())
            count++;
        }

        if (count == strlen(str))
            printf("%s is a palindrome\n", str);
        else
            printf("%s is not a palindrome\n", str);

    }

    return 0;
}

void push(char word)
{
    top=top+1;
    stack_string[top]=word;
}

 char pop()
{
    word = stack_string[top];
    top=top-1;
    return word;
}

最佳答案

使用这个:

scanf(" %[^\n]s", str);
      ^^^
    Whitespace

而不是

scanf("%[^\n]s", str);

欲了解更多信息,请参阅this链接。

关于c - 我的 scanf 函数在 if 函数内部不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43752219/

相关文章:

c - 空括号中的星号是什么意思?

带有 fork() 和 pipe() 的 C 并行服务器

c - MPI_Isend 段错误

C编译错误: undeclared (first use in this function)

c - 在 C 中实现基本的 Raytracer

c - 用一个物理定时器模拟多个虚拟定时器

c - LED 保持亮起。不会打开和关闭

c - Redis 中 RedisModule_Alloc() 的自动内存管理

c - 为 shell 程序标记 char*

c - 扫描文本文件时如何跳过一行?