我试图研究有关我的问题的各个站点,但是我仍然不明白代码出了什么问题。
我没有得到想要的写入字符串,而是得到了一个随机的100长数字和char组合(以输入的字符串开头,后跟定界符),它等于null。
#include <stdio.h>
#include <string.h>
int main()
{
char message[100], ans;
int key = 3;
printf("Enter a message:");
scanf("%s", message); //keeps on going until reaches 100 random characters and numbers
printf("Encrypt [E] or decrypt [D]?: ");
scanf("%s", &ans);
}
我已经在线尝试了各种方法,但是似乎都没有用。
编辑: 即使我尝试了一个简单的字符串程序也不起作用
#include <stdio.h>
#include <string.h>
int main()
{
char message[100];
printf("Enter a message:");
scanf("%s", message);
printf("Encrypted message: %s", message[100]);
}
我正在通过dev c ++控制台提供输入。
请注意,定界符(单词后的“ \”)实际上并没有发挥作用。
EDIT3:这是程序的全部代码
#include <stdio.h>
#include <string.h>
void decryptmessage(char message[], int key)
{
char ch;
int i;
for(i = 0; message[i] != '\0'; ++i){
ch = message[i];
if(ch >= 'a' && ch <= 'z'){
ch = ch - key;
if(ch < 'a'){
ch = ch + 'z' - 'a' + 1;
}
message[i] = ch;
}
else if(ch >= 'A' && ch <= 'Z'){
ch = ch - key;
if(ch < 'A'){
ch = ch + 'Z' - 'A' + 1;
}
message[i] = ch;
}
}
printf("Decrypted message: %s", message);
}
void encryptmessage(char message[], int key)
{
char ch;
int i;
for(i = 0; message[i] != '\0'; ++i){
ch = message[i];
if(ch >= 'a' && ch <= 'z'){
ch = ch + key;
if(ch > 'z'){
ch = ch - 'z' + 'a' - 1;
}
message[i] = ch;
}
else if(ch >= 'A' && ch <= 'Z'){
ch = ch + key;
if(ch > 'Z'){
ch = ch - 'Z' + 'A' - 1;
}
message[i] = ch;
}
}
printf("Encrypted message: %s", message);
}
int main()
{
char message[100], ans;
int key = 3;
printf("Enter a message:");
scanf("%s", message);
printf("Encrypt [E] or decrypt [D]?: ");
scanf("%c", &ans);
if (ans == 'E') //this has to be substituted by its numerical value
encryptmessage(message, key);
else if (ans == 'D') //same as line 78
decryptmessage(message, key);
else
printf("Goodbye.");
return 0;
}
现在,当消息按预期运行时,字符ans 会自动变为10,而无需让我输入。 我真的不知道为什么。
答案 0 :(得分:2)
您要告诉调试器显示100个字符的缓冲区的内容,这就是它的作用。它显示了100个字符。如果您想知道缓冲区中的字符串,则只需在第一个\000
之后停止读取,或使用printf
显示其中包含的字符串。
答案 1 :(得分:2)
您希望用户输入字符串时将“ ans”创建为字符,因此应使用%c从输入中获取字符变量。 编辑:在您的“只是扫描并打印一个字符串”上,我试图运行它,问题出在打印部分,您正在打印“ message [100]”,该字符串不存在,因为字符串具有0-99的位置,您只需打印“消息”
答案 2 :(得分:-1)
EDIT4:现在可以正常工作了,问题不是“%c”。
对于任何在问问题之前问我为什么不这样做的人:我做了,但是由于某些原因它仍然不能正常工作。
谢谢大家的帮助。