我是編程新手。我對字串有基本的懷疑。
我可以成功列印用戶給出的字串。但是當我運行 Caesar Cipher 的代碼時,事情變得很奇怪。
以下代碼將解釋實際問題出在哪里。
在下面的代碼中,我能夠成功列印我輸入的字串:
#include <stdio.h>
int main()
{
char str[20];
printf("Enter a string\n");
scanf("%[^\n]s",&str);
printf("The entered string is %s",str);
}
輸出:
或(使用 for 回圈如下)
#include <stdio.h>
int main()
{
char str[20],i;
printf("Enter a string\n");
scanf("%[^\n]s",&str);
printf("The entered string is:");
for(i=0;i<=20;i )
{
if(str[i]=='\0')
break;
printf("%c",str[i]);
}
}
輸出:
我知道在每個字串的末尾都有 \0 來標記字串的結尾。
但是,如果我嘗試在上述方法中列印 Caesar Cipher,事情就會變得不順利。(這里我宣告了一個長度為 20 的字符陣列,正如我在實驗室會話中被告知這樣做的那樣。我附上了我的實際實驗室最后的問題)
第一種方法
#include <stdio.h>
int main()
{
char str[20],shift_str[20];
int n;
printf("Enter a string\n");
scanf("%[^\n]s",&str);
printf("Enter a number to shift the string:");
scanf("%d",&n);
int i,s,p;
for(i=0;i<=20;i )
{
if(str[i]=='\0')
break;
s=(int)str[i];//type casting str to get the ASCII Value
p=n s;
shift_str[i]=(char)p;// type casting the shifted ASCII Value to char
}
printf("Caesar Cipher is:%s",shift_str);
}
輸出:
第二種方法(使用for回圈):
#include <stdio.h>
int main()
{
char str[20],shift_str[20];
int n;
printf("Enter a string\n");
scanf("%[^\n]s",&str);
printf("Enter a number to shift the string:");
scanf("%d",&n);
int i,s,p;
for(i=0;i<=20;i )
{
if(str[i]=='\0')
break;
s=(int)str[i];//type casting str to get the ASCII Value
p=n s;
shift_str[i]=(char)p;// type casting the shifted ASCII Value to char
}
for(i=0;i<=20;i )
{
if(shift_str[i]=='\0')
break;
printf("%c",shift_str[i]);
}
}

As you can see the coding is running fine expect for the fact that it is printing some junk value stored in the array after the desired output.
As far as I have learned, shift_str should have '\0' after "Ifmmp!Xpsme" so the string should terminate after it, but rather it goes on to print the junk values in the rest of the array as well!!
So at first I would like to know why is it working in that way, and second what is the correct code to run my Caesar Cipher.
I would be glad to receive any help.
(I have originally posted this question in "code review stack", that later found that was not the correct place to ask this type of question as "code review" is meant for improving already successful coed.My apologies)
My original lab question:

uj5u.com熱心網友回復:
我知道在每個字串的末尾都有 \0 來標記字串的結尾。
您似乎不明白這一點,因為您沒有在末尾放置這樣的標記,shift_str而是將其用作字串。在你的代碼,shift_str是不是一個字串,因為沒有\ 0在它的結束,因此它是將它傳遞給一個錯誤printf通過%s。
也許改變:
if(str[i]=='\0')
break;
到
if(str[i]=='\0')
{
shift_str[i]='\0';
break;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/400285.html
標籤:c
下一篇:輸出不是我從代碼中所期望的
