无法在字符串中添加int,尝试使用sprintf,但我遇到了麻烦

时间:2014-10-09 23:43:33

标签: c printf strcpy

我正在尝试读取文件并打印文件中的所有单词,忽略所有其他空格和符号。我让它使用strcpy,但它给了我一个错误,我试图使用sprintf,但我真的不明白这个功能词是怎么回事。它打印随机整数而不是字符串。

编辑:我对C来说是全新的,所以我的指针不太好。

  FILE *file;
  file = fopen("sample_dict.txt", "r");
  int c;
  int wordcount = 0;
  int count = 0;
  const char *a[10];
  char word[100];
  do {
    c = fgetc(file);
    //error statement
    if (feof(file)) {
      break;
    }
    if (isalpha(c) && count == 2) {
      printf("%s\n", word);
      memset(word, 0, sizeof(word));
      count = 1;
      wordcount++;
    }

    if (isalpha(c)) {
      //strcat(word, &c);
      sprintf(word, "%d", c);
      continue;
    }
    count = 2;
    continue;
  } while (1);
  fclose(file);
  return (0);

  return 0;

2 个答案:

答案 0 :(得分:1)

如果需要该字符,请在C中使用%c作为格式说明符。如果使用%d,它将起作用,但会显示为整数 另一件事是,如果你想使用sprintf将字符串与char或int连接起来,你必须在sprintf的参数列表中包含两者:

改变这个:

sprintf(word, "%d", c);

对此:

char newString[20];//adjust length as necessary
sprintf(newString, "%s%c",word, c);  

你的逻辑表明你只想附加char,如果它是alpha [a-z,A-Z]

  if(isalpha(c))
  {
    //strcat(word, &c);
    sprintf(word, "%d", c);
    continue;
  }  

将其更改为:

  if(isalpha(c))
  {
    //strcat(word, &c);
    char newString[20];//bigger if needed, 20 just for illustration here
    sprintf(newString, "%s%d", word, c);
    continue;
  }    

答案 1 :(得分:0)

#define IN 1
#define OUT 0

FILE *file;
file = fopen("sample_dict.txt","r");
int c;
int wordcount = 0;
int status = OUT;//int count = 0;
//const char *a[10];//unused
char word[100] = "";

do {
    c = fgetc(file);
    if(feof(file)){
        if(*word){//*word : word[0] != '\0'
            printf("%s\n", word);
        }
        break;
    }
    if(isalpha(c)){
        char onechar_string[2] = {0};//{c};
        onechar_string[0] = c;
        strcat(word, onechar_string);
        if(status == OUT){
            wordcount++;
        }
        status = IN;
    } else {
        if(status == IN){
            printf("%s\n", word);
            *word = 0;//memset(word,0,sizeof(word));
        }
        status = OUT;
    }
}while(1);
fclose(file);
相关问题