簡體   English   中英

無法在字符串中添加整數,嘗試使用sprintf但我遇到了麻煩

[英]Having trouble adding an int to a string, tried using sprintf but I'm having trouble

我正在嘗試讀取文件並打印文件中的所有單詞,而忽略所有其他空格和符號。 我在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;

如果需要字符,請在C中將%c用作格式說明符。 如果使用%d,它將起作用,但是將顯示為整數。
另一件事是,如果要使用sprintf將一個字符串與char或and int串聯,則必須在sprintf的參數列表中都包括這兩者:

改變這個:

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

對此:

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

您的邏輯在這里建議您只想附加字符,如果它是字母[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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM