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

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

编辑:我对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; 

如果需要字符,请在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 [az,AZ]

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