将 int 添加到字符串时遇到问题,尝试使用 sprintf 但我遇到了问题 [英] Having trouble adding an int to a string, tried using sprintf but I'm having trouble

查看:58
本文介绍了将 int 添加到字符串时遇到问题,尝试使用 sprintf 但我遇到了问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我对 C 完全陌生,所以我的指针不太好.

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;

推荐答案

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

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:

改变这个:

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

为此:

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

你在这里的逻辑表明你只想附加字符,如果它是一个 alpha [a-z,A-Z]

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

改为:

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

这篇关于将 int 添加到字符串时遇到问题,尝试使用 sprintf 但我遇到了问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆