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

标签 c string function file-io

这个程序应该将一个句子移动一定量。 如果我的类次是 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/

相关文章:

c - *++*p 是可接受的语法吗?

c - 删除 Kernighan 和 Ritchie 的评论程序

c - C中的图像/二维数组重采样

javascript - jQuery - 显示变量,而不是文本字符串

language-agnostic - 如果尚不存在,则用于创建某物的函数名称

c - 如何将 'build' 的一个 long 值从 2 个 int 值拆分回其 2 个整数?

c++ - 不推荐从字符串常量到 'char*' 的转换

javascript - (JavaScript) 在其他函数的回调中执行函数

c - 警告 : passing argument 1 of makes integer from pointer without a cast [enabled by default]

python - 为函数提供多个参数