gpt4 book ai didi

C 程序将文件 io 传递给函数

转载 作者:太空宇宙 更新时间:2023-11-04 03:35:07 25 4
gpt4 key购买 nike

这个程序应该将一个句子移动一定量。如果我的类次是 3,那么字母 a 应该是 d。但是,当我将字符串传递到我的 shift 函数时,它不会改变我的任何值。

#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;

scanf("%d", &shift_by);

ifp = fopen("input.txt", "r");
ofp = fopen("output.txt", "w");

if (ifp == NULL) {
printf("FILE doesnt open");
return 1;
}

while(fgets(str, MAX_LEN, ifp) != NULL) {
shift(str, shift_by);
fprintf(ofp," %s", str);
}

fclose(ifp);
fclose(ofp);
return 0;
}

void decode(char *sentence, int shift)
{
char *p;
p = sentence;

if ((*p >= 'a') && (*p <= 'z')) {
*p = (*p - 'a') + shift % 26 + 'a';
}

if ((*p >= 'A') && (*p <= 'Z')) {
*p = (*p - 'A' + shift) % 26 + 'A';
}

}

最佳答案

请尝试下面的代码。你以为是“解码”,但你输入的是“转变”。我稍微简化了代码。现在你可以尝试让它与指针一起工作。玩得开心。

#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;

printf( "\nPlease enter shift by and press enter\n" );
scanf( " %d", &shift_by );

ifp = fopen( "input.txt", "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++;
}

}

关于C 程序将文件 io 传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33312957/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com