我正在尝试读取包含字符串“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);
}
最佳答案
如果您只是想从输入中过滤掉任何非数字,则无需使用 scanf
、sprintf
等。只需循环缓冲区并复制数字字符即可。
以下程序仅适用于从标准输入读取的单行输入,并且仅当它的长度小于 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/