C程序将file-io传递给函数

时间:2015-10-23 23:41:41

标签: c string function file-io

该程序应该将一个句子移动一定数量。 如果我的班次为3,则字母a应为d。但是当我将字符串传递给我的移位函数时,它不会移动我的任何值。

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

}

1 个答案:

答案 0 :(得分:1)

请尝试下面的代码。你以为&#39;解码&#39;但你键入了'shift&#39;。我稍微简化了代码。现在,您可以尝试使其与指针一起使用。 玩得开心。

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

}