首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >C代码行为怪异。有时需要输入,有时不需要

C代码行为怪异。有时需要输入,有时不需要
EN

Stack Overflow用户
提问于 2021-11-22 09:58:01
回答 1查看 65关注 0票数 0

我正在制作一个多功能的命令行应用程序,其中用户具有诸如加密-解密字符串、检查字符串回文和反转字符串等功能,并且我开始使用加密-解密功能编写我的整个代码,但显然它不能像预期的那样工作,有时它会加密/解密字符串,相同的代码在再次执行时不接受字符串输入就会退出!我甚至插入了fflush(stdin),但没有成功!

代码语言:javascript
运行
复制
#include <stdio.h>

void encryptDecrypt();
// void checkPalindrome();
// void reverseWord();

void main()
{
    int choice;
    printf("\nWelcome to Jeel's multi-feature C App\n\n");
    printf("1. Encrypt-Decrypt a word\t2. Check Palindrome\t3. Reverse a word\n\n");
    printf("Enter a feature: ");
    scanf("%d", &choice);
    switch (choice)
    {
    case 1:
        fflush(stdin);
        encryptDecrypt();
        break;

    case 2:
        // checkPalindrome();
        break;

    case 3:
        // reverseWord();
        break;

    default:
        break;
    }
}

void encryptDecrypt()
{
    fflush(stdin);
    char eOrD;
    printf("\nWelcome to the World of Encryption & Decryption! We're so glad that you're here!\n\n");
    printf("Enter 'e' if you want to encrypt a word or 'd' if you want to decrypt a word (e/d): ");
    scanf("%c", &eOrD);
    if (eOrD == 'e' || eOrD == 'E')
    {
        fflush(stdin);
        char *word;
        printf("\nGreat! Now enter a word to encrypt it: ");
        fflush(stdin);
        gets(word);

        char *ptr = word;
        for (int i = 0; i < sizeof(ptr); i++)
        {
            if (*ptr != '\0')
            {
                *ptr = *ptr + 7;
                ptr++;
            }
        }
        printf("\nEncrypted string is: %s, which is encrypted with the key: %d", word, 7);
    }
    else if (eOrD == 'd' || eOrD == 'D')
    {
        fflush(stdin);
        char *deWord;
        printf("\nGreat! Now enter a word to decrypt it: ");
        gets(deWord);
        char *dePtr = deWord;
        for (int i = 0; i < sizeof(dePtr); i++)
        {
            if (*dePtr != '\0')
            {
                *dePtr = *dePtr - 7;
                dePtr++;
            }
        }
        printf("\nDecrypted string is: %s, which is decrypted with the key: %d\n", deWord, 7);
    }
    else
    {
        printf("Invalid input! Please try again!");
    }
}
EN

Stack Overflow用户

回答已采纳

发布于 2021-11-22 10:07:41

清除stdin的最佳和最便携的方法是使用以下代码:

代码语言:javascript
运行
复制
void clearStream()
{
    int c;
    while ((c = getchar()) != '\n' && c != EOF) { }
}

同样,下面的内容也是不正确的,请创建一个数组而不是指针:

代码语言:javascript
运行
复制
char *word;
gets(word); //word is a pointer, gets will not create a block of memory for it
票数 0
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70063899

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档