该程序采用包含特定句子的文件名并移动一定量 .
如果我有 Hello 并且移动了22它应该是 Dahhk ,当我没有输入文件名并且在程序中手动输入文件名时,这个工作正常
ifp = fopen(“input.txt”,“r”);
但是,当我让用户输入文件名并且输入为 Hello 并且移位22时,输出变为 D{‚‚…
ifp = fopen(name,“r”);
我尝试使用scanf(“%s”,名字);
我尝试使用fgets(name,sizeof(name),stdin);
两者都产生相同的结果
我不知道如何解决这个问题 .
#include <stdio.h>
#define MAX_LEN 100
void decode( char *sentence, int shift );
int main( void )
{
FILE *ifp;
FILE *ofp;
char str[MAX_LEN];
int shift_by = 0;
char name[100];
printf("Program name: \n");
scanf("%s", name);
printf( "Please enter shift by and press enter\n" );
scanf( " %d", &shift_by );
ifp = fopen( name, "r" );
ofp = fopen( "output.txt", "w" );
if ( ifp == NULL )
{
printf( "FILE doesnt open" );
return 1;
}
while ( fgets( str, MAX_LEN, ifp ) != NULL )
{
decode( str, shift_by );
fprintf( ofp, " %s", str );
}
fclose( ifp );
fclose( ofp );
return 0;
}
void decode( char *sentence, int shift )
{
int i = 0;
char p;
while ( p = sentence[i] )
{
if ( ( p >= 'a' ) && ( p <= 'z' ) )
{
p = ( p - 'a' ) + shift % 26 + 'a';
}
if ( ( p >= 'A' ) && ( p <= 'Z' ) )
{
p = ( p - 'A' + shift ) % 26 + 'A';
}
sentence[i] = p;
i++;
}
}
1 回答
OP的代码有一个小错误:
好奇的OP编码正确
提示是“你好” - >“D {,, ......”适用于大写,但不是小写 .