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

血红的双手。 提交于 2019-12-12 04:53:01

问题


I am trying to read a file and print all of the words that are in the file, ignoring all other spaces and symbols. I have it working with strcpy but it's giving me an error and I'm trying to use sprintf but I don't really understand how that function words. It's printing random integers instead of the strings.

Edit: I'm completely new to C so I don't have my pointers down too well.

  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;

回答1:


Use a %c for a format specifier in C if you want the character. if you use %d, it will work, but will display as integer.
The other thing is that if you want to use sprintf to concatenate a string with a char, or and int, you must include both in the argument list of sprintf:

change this:

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

To this:

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

Your logic here suggests that you only want to append the char, if it is an alpha [a-z,A-Z]

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

Change it to:

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



回答2:


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


来源:https://stackoverflow.com/questions/26289719/having-trouble-adding-an-int-to-a-string-tried-using-sprintf-but-im-having-tro

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!