gpt4 book ai didi

C 程序跳过 printf 和 scanf 语句

转载 作者:行者123 更新时间:2023-11-30 19:05:06 24 4
gpt4 key购买 nike

下面的程序用 C 语言执行凯撒密码。出于某种原因,在用户输入消息后, printf("\nEnter key:")scanf("%d", &key) 语句被“跳过”。我的想法是与输入缓冲区有一个字符和换行符输​​入导致跳转有关(因此是 fflush 尝试)。我该如何防止这种行为?

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

int main() {
char message[50], ms;
int i, key, choice;

printf("Enter 1. to Encrypt, or 2. to Decrypt: ");
scanf(" %d", &choice);

printf("Enter a message to process: ");
scanf(" %c", message);
printf(" \nEnter key:");
fflush(stdin);
scanf("%d", &key);

for (i = 0; message[i] != '\0'; ++i) {
ms = message[i];
if (ms >= 'a' && ms <= 'z' && choice == 1) {
ms = ms + key;
if (ms >= 'a' && ms <= 'z' && choice == 2) {
ms = ms - key;
if (ms > 'z') {
ms = ms - 'z' + 'a' - 1;
}
}
message[i] = ms;
} else
if (ms >= 'A' && ms <= 'Z' && choice == 1) {
ms = ms + key;
if (ms >= 'A' && ms <= 'Z' && choice == 2) {
ms = ms - key;
}
if (ms > 'Z') {
ms = ms - 'Z' + 'A' - 1;
}
message[i] = ms;
}
if (choice == 1) {
printf(" \nEncrypted message: %s", message);}
else if (choice == 2) {
printf(" \nDecrypted message: %s", message);}
}
}

最佳答案

@ddisec 我已经注意到3 mistakes在您的代码中。

首先是你的scanf(" %c", message); .这里你必须使用%s (字符串)

其次,结果打印语句应该在 for-loop 之外.

第三次推杆if(ms >= 'a' && ms <= 'z'&& choice == 2)里面if (ms >= 'a' && ms <= 'z' && choice == 1)没有任何意义。

试试这个更正后的代码:-

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

int main()
{
char message[50], ms;
int i, key, choice;

printf("Enter 1. to Encrypt, or 2. to Decrypt: ");
scanf("%d", &choice);
getchar(); // to handle unwanted newline.
printf("Enter a message to process: ");
scanf("%49[^\n]", message);
printf(" \nEnter key:");
scanf("%d", &key);

for (i = 0; message[i] != '\0'; ++i)
{
ms = message[i];
if (ms >= 'a' && ms <= 'z' && choice == 1)
{
ms = ms + key;
}
else if (ms >= 'a' && ms <= 'z' && choice == 2)
{
ms = ms - key;
}
else if (ms > 'z')
{
ms = ms - 'z' + 'a' - 1;
}
else if (ms >= 'A' && ms <= 'Z' && choice == 1)
{
ms = ms + key;
}
else if (ms >= 'A' && ms <= 'Z' && choice == 2)
{
ms = ms - key;
}
else if (ms > 'Z')
{
ms = ms - 'Z' + 'A' - 1;
}

message[i] = ms; // Only single modification code needed.
}
if (choice == 1)
{
printf(" \nEncrypted message: %s", message);
}
else if (choice == 2)
{
printf(" \nDecrypted message: %s", message);
}
}

关于C 程序跳过 printf 和 scanf 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50555256/

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