该程序采用包含特定句子的文件名并按一定量移动。
如果我有 Hello 并移动 22 它应该是 Dahhk,当我没有输入文件名并且在程序中有文件名时这工作正常手动点赞
ifp = fopen( "input.txt", "r" );
然而,当我让用户输入文件名并且输入是 Hello 并移动 22 时,输出变为 D{‚‚…
ifp = fopen( name, "r" );
我尝试使用 scanf("%s", name);
我尝试使用 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++;
}
}
最佳答案
OP的代码有个小错误:
// p = ( p - 'a' ) + shift % 26 + 'a';
p = ( p - 'a' + shift) % 26 + 'a';
奇怪的是 OP 用
正确编码p = ( p - 'A' + shift ) % 26 + 'A';
提示是“Hello”-->“D{‚‚…”适用于大写,但不适用于小写。
关于C程序文件-io用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33319549/