我正在使用Caesar密码,一切似乎都运行良好,除了在我的句子结尾处我得到了一大堆非alpha数字乱码。我几乎肯定这是由于有额外的数组空间,但我需要允许用户输入100个字符,C似乎没有相当于arraylist所以我不知道怎么去摆脱这个问题。这是我的代码
#include <stdio.h>
#include <ctype.h>
int main ()
{
/* Declare variables to store sentence and shift number.
i is used for loops, mod temporarily stores input[i] + shift */
char input[100];
int mod;
int shift;
int i=0 ;
printf("sentence ");
fgets(input, 100, stdin); //fgets stores user input for sentence
//while setting a maximum size
// prompts user to set shift, then mods it to ensure shift stays
// between 0-26
printf("\n Number");
scanf( "%d" , &shift);
shift = shift % 26;
//printf( "%d", input[1]);
/* loops. for loop scans through input, and if statements
* insure input[i] is an alphabet letter and classify
* it to the letter's respective case. */
for ( i =0 ; i < 100 ; i++) {
if ( isupper(input[i])) {
mod = input[i] + shift;
if (mod > 90) { mod -= 26;}
if (mod < 65) { mod += 26;}
printf( "%c", mod ); }
else if( islower(input[i])) {
mod = input[i] + shift;
if (mod > 122) { mod -= 26;}
if (mod < 97) { mod += 26;}
printf( "%c", mod ); }
// my unsuccesful attempt at ignoring empty array spaces
else if ( input[i] != 000) {
printf( "%c", input[i]);
}
}
return 0;
}
答案 0 :(得分:1)
无论字符串长度如何,您都处理了100个字符。因此,不要循环遍历100个字符,而只检查字符串的长度。
for ( i =0 ; i < strlen(input) ; i++) { ... }