gpt4 book ai didi

C:如何读取文本文件并在某个点之后获取某些值?

转载 作者:行者123 更新时间:2023-11-30 16:36:58 25 4
gpt4 key购买 nike

所以基本上文本文件看起来像这样

Starting Cash: 1500
Turn Limit (-1 for no turn limit): 10
Number of Players Left To End Game: 1
Property Set Multiplier: 2
Number of Houses Before Hotels: 4
Must Build Houses Evenly: Yes
Put Money In Free Parking: No
Auction Properties: No
Salary Multiplier For Landing On Go: 1

我从文件中需要的基本上是“:”之后的任何内容我只是很困惑如何只读取“:”之后的任何内容?这就是我现在所拥有的。我似乎想不出一种只扫描数字/yesorno 的方法。

void readRules(char*file_name)
{
Rules r;
FILE *file = NULL;
file = fopen(file_name, "r");

if (file == NULL) {
printf("Could not open %s\n", file_name);
return;
}
char c=fgetc(file);
fscanf(file, "%c", &c);
while (!feof(file))
{
fscanf(file, "%c", &c);
if(c==':')
{
r.startCash=c;
}
}

printf("There are %c word(s).\n", r.startCash);

fclose(file);
}

谢谢。

最佳答案

该程序将读取给定文件的每一行中冒号后面的整数。我想这样合适吗?冒号后面还有一些字符串。如果您想阅读这些内容,可以尝试扫描字符串“%s”并测试函数是否返回非零(至少匹配一种格式模式)。

#include <stdio.h>
#include <stdlib.h>

#define MAXLINE 1000

void readRules (const char *filename) {
FILE *fp;
char *lp, line[MAXLINE];
int n;

// Return early if file cannot be opened.
if ((fp = fopen(filename, "r")) == NULL) {
fprintf(stderr, "Error: Couldn't open \"%s\"!\n", filename);
return;
}

// Use fgets to read consecutive lines. Returns NULL on error or EOF.
while (fgets(line, MAXLINE, fp) != NULL) {

// Read until newline is hit or buffer size exceeded.
for (lp = line; *lp != '\n' && (lp - line) < MAXLINE; lp++) {

// If encounter colon and sccanf reads at least 1 integer..
if (*lp == ':' && sscanf(lp + 1, "%d", &n) == 1) {
fprintf(stdout, "%d\n", n);
break;
}
}
}


// Clean up.
fclose(fp);
}

int main (int argc, const char *argv[]) {
readRules("test.txt");
return 0;
}

当使用示例输入运行时,它会生成:

1500
10
1
2
4
1

关于C:如何读取文本文件并在某个点之后获取某些值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48222138/

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