gpt4 book ai didi

c - 使用tab在文件中查找int,c编程

转载 作者:行者123 更新时间:2023-11-30 20:38:48 25 4
gpt4 key购买 nike

我有一个小问题,我需要在文件中找到 3 个整数,如下所示:

some variable text size here \t int \t int \t n  (just tabs no space)

some variable text size here1 \t int \t int \t n (just tabs no space)

我的问题是如何在可变文本大小中查找 int,我的第一个想法是使用 fscanf:

 fscanf (file, "%d\t%d\t%d",&firs,&second,&third) 

但是这不起作用,或者读取 char 缓冲区中的整行,然后以某种方式找到制表符,然后在制表符后提取 int。请一些帮助。

最佳答案

#include <stdio.h>
#include <string.h>
#include <ctype.h>

int char1(const char **p, char ch){
if(**p == ch){
++*p;
return 1;
}
return 0;
}

static inline int tab(const char **p){
return char1(p, '\t');
}
static inline int hyphen(const char **p){
return char1(p, '-');
}
int repeat1(const char **p, int (*test)(int)){
//test : test character type (e.g isdigit)
//[character kind]+
const char *tmp = *p;
while(test(**p))
++*p;
return *p != tmp;
}
int repeatpn(const char **p, int (*parser)(const char **), int n){
const char *tmp = *p;
if(n<1) return 0;
while(n && parser(p))
--n;
if(n != 0){
*p = tmp;
return 0;
}
return 1;
}
static inline int digits(const char **p){
return repeat1(p, isdigit);
}
static inline int natural(const char **p){
return digits(p);//Alias, allow start 0 (e.g 012)
}
int negative_integer(const char **p){
const char *tmp = *p;
if(hyphen(p) && natural(p))
return 1;
*p = tmp;
return 0;
}
static inline int integer(const char **p){
//note : does not mean the range of int
return natural(p) || negative_integer(p);
}
int tabAndInteger(const char **p){
const char *tmp = *p;
if(tab(p) && integer(p))
return 1;
*p = tmp;
return 0;
}
int my_match(const char **p){
//(\t\d+){3}
return repeatpn(p, tabAndInteger, 3);
}

int main(void){
FILE *file = fopen("data.txt", "r");
char text[256];
int v1, v2, v3;
while(fgets(text, sizeof text, file)){
const char *p = strchr(text, '\t'), *tmp = p;
if(my_match(&tmp)){//\t\d+\t\d+\t\d+
sscanf(p, "%d%d%d", &v1,&v2,&v3);
printf("%d, %d, %d\n", v1, v2, v3);
}
}
fclose(file);
return 0;
}

关于c - 使用tab在文件中查找int,c编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28120991/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com