Strlen返回实际长度+2

时间:2019-01-25 13:39:16

标签: c

为什么strlen返回6而不是4,即使文件包含4个字母的单词,单词之后也没有空格?

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void leggi_file(FILE *in, char *s);
char * vect(char *s);
int pal(char *);

int main(void){
    FILE *in;
    char *s[100], *v;
    int n;
    in = fopen("testfile", "r");
    leggi_file(in,*s);
    printf("%s",*s);
    v = vect(*s);
    printf("%s",v);
    n = pal(*s);
    printf("%d",n);
    int dim = strlen(*s);
    printf("%d",dim);
    return 0;
}

void leggi_file(FILE *in, char *s){
    int c, count = 0;
    while((c=getc(in))!=EOF && count < 100){
        s[count] = c;
        count++;
    }
}

char * vect(char *s){
    char *vect;
    int dim = strlen(s);
    vect = malloc((dim+1)*sizeof(char));
    vect = s;
    return vect;
}

int pal(char *s){
    int i, tmp, dim;
    dim = strlen(s);
    tmp=dim-1;
    for(i=0; i<(dim/2); i++){
        if(*(s+i) != *(s+tmp))
            return 0;
        else
            tmp--;
    }
    return 1;
}

testifile包含“ anna”

1 个答案:

答案 0 :(得分:0)

您可能想要这个。注释中有解释。尽管如此,仍有进一步改进的空间。

我不确定呼叫vect的目的是什么。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void leggi_file(FILE *in, char *s);
char *vect(char *s);
int pal(char *);

int main(void) {
  FILE *in;
  char s[100], *v;   // just use s, you want an array of char, not an array of
  int n;             //  pointers to char
  in = fopen("data.txt", "r");
  if (in == NULL)  // check if file could actually be opened
  {
    printf("Can't open file\n");
    exit(1);
  }
  leggi_file(in, s);
  fclose(in);       // close file
  printf("%s", s);
  v = vect(s);
  printf("%s", v);
  n = pal(s);
  printf("%d", n);
  int dim = strlen(s);
  printf("%d", dim);
  free(v);           // free memory
  return 0;
}

void leggi_file(FILE *in, char *s) {
  int c, count = 0;
  while ((c = getc(in)) != EOF && count < 100) {
    if (c == '\n')  // stop on first end of line
      break;
    s[count] = c;
    count++;
  }

  s[count] = 0;   // put string terminator, omitting this
}                 // was one of the major problems in your code

char * vect(char *s) {
  char *vect;
  int dim = strlen(s);
  vect = malloc((dim + 1) * sizeof(char));
  strcpy(vect, s);    // copy string
  return vect;
}

int pal(char *s) {
  int i, tmp, dim;
  dim = strlen(s);
  tmp = dim - 1;
  for (i = 0; i < (dim / 2); i++) {
    if (*(s + i) != *(s + tmp))
      return 0;
    else
      tmp--;
  }
  return 1;
}

(*(s + i) != *(s + tmp))的可读性更好(s[i] != s[tmp])完全等效。