c - 读取文本文件,将所有数字保存到字符串中

标签 c file input

我正在尝试读取包含字符串“a3rm5t?7!z*&gzt9v”的文本文件,并将所有数字字符放入字符串中,以便稍后转换为整数。

我目前正在尝试通过在读取文件后在缓冲区上使用 sscanf 来实现此目的,然后使用 sprintf 保存在名为 str 的字符串中使用 %u 找到的所有字符。

但是,每次运行程序时,在 str 上调用 printf 时返回的整数都是不同的。我做对了什么,做错了什么?

当文本文件包含像“23dog”这样的字符串并返回 23 时,此代码有效,但当字符串是像 23dog2 这样的字符串时,此代码不起作用。

编辑:我现在意识到我应该将数字字符放入字符数组中,而不仅仅是一个字符串中。

int main(int argc, const char **argv)
{
    int in;
    char buffer[128];
    char *str;
    FILE *input;

    in = open(argv[1], O_RDONLY);
    read(in, buffer, 128);

    unsigned x;
    sscanf(buffer, "%u", &x);
    sprintf(str,"%u\n", x);
    printf("%s\n",str);

    close (in);

    exit(0);
}

最佳答案

如果您只是想从输入中过滤掉任何非数字,则无需使用 scanfsprintf 等。只需循环缓冲区并复制数字字符即可。

以下程序仅适用于从标准输入读取的单行输入,并且仅当它的长度小于 512 个字符时,但它应该为您提供正确的想法。

#include <stdio.h>

#define BUFFER_SIZE 512

int
main()
{
  char buffer[BUFFER_SIZE];  /* Here we read into. */
  char digits[BUFFER_SIZE];  /* Here we insert the digits. */
  char * pos;
  size_t i = 0;
  /* Read one line of input (max BUFFER_SIZE - 1 characters). */
  if (!fgets(buffer, BUFFER_SIZE, stdin))
    {
      perror("fgets");
      return 1;
    }
  /* Loop over the (NUL terminated) buffer. */
  for (pos = buffer; *pos; ++pos)
    {
      if (*pos >= '0' && *pos <= '9')
        {
          /* It's a digit: copy it over. */
          digits[i++] = *pos;
        }
    }
  digits[i] = '\0';  /* NUL terminate the string. */
  printf("%s\n", digits);
  return 0;
}

关于c - 读取文本文件,将所有数字保存到字符串中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26089308/

相关文章:

当 int 变量在循环内更新时,C 代码不起作用

java - 输入输出异常处理

HTML - 带有分钟和秒的自定义输入

objective-c - 如何从 SQLite3 行中获取日期或日期时间?

c - 如果达到最大大小或单击了 "enter",如何告诉 scanf 对字符进行索引?

java - 读取文本文件并打印图形

java - 在 MATLAB 中读取文件时指定数据类型

java - 当我尝试在驱动器中搜索时程序抛出 NullPointerException?

c - 如何在循环时扫描输入(C 程序)

c - Makefile:为什么带有 % 的 makefile 不起作用?