gpt4 book ai didi

C fscanf 复杂格式

转载 作者:太空宇宙 更新时间:2023-11-04 08:01:29 24 4
gpt4 key购买 nike

我正在尝试从 C 文件中读取此文本。假设这是文件 Input.txt

This is a description which can be up to 1024 characters long
First
Second
Thrid Option This is a description for third
Fourth

我要读第一第二第三第四这4个字,剩下的就是丢弃。我有这个问题的解决方案,但我不明白它为什么有效:

char string[1024];
char words[4][256];
FILE *in = fopen("Input.txt", "r");

// Catch first line
fgets(string, 1024, in);

for(int i = 0; i < 4; i++){
fscanf(in, "%255s[^\n]\n", words[i]);
fscanf(in, "%*[^\n]\n");
}

输入文件需要特殊格式。

  • 第一行是描述,最长可达 1024 个字符。
  • 第 2 到 5 行始终采用以下格式:“Word tab Option tab Description ”。 Word 是必填项,Option 和 Description 是可选的(例如参见 Input.txt)

如果能解释格式字符串的不同组成部分、它们的工作原理以及整个解决方案为何有效,我将不胜感激。

(我也找不到任何关于 fscanf 格式如何工作的具体信息,如果有人能给我引用,我会很高兴)

最佳答案

“以及为什么整个解决方案有效”IMO,在一般情况下,它不会。

2 个 fscanf(in, ... 格式中的第二个 '\n' 使它成为一个弱解决方案。那个 '\n' 将扫描任意数量的换行符以及任何空白。最好继续使用 fgets(string, ...) 然后 sscanf(string, ...)

"%255s[^\n]\n""%255s" 之后查找 [。奇怪的代码。 @John Bollinger


代替

char string[1024+1+1];  // increase for the \n and the \0
char words[4][256];
FILE *in = fopen("Input.txt", "r");

// Catch first line
// fgets(string, 1024, in);
fgets(string, sizeof string, in);

// "%255s"
// scan over yet do not save leading white-space
// scan and save up to 255 non-white-space characters.
// Append a null character to form a string
for(int i = 0; i < 4 && fgets(string, sizeof string, in); i++ ){
if (sscanf(string, "%255s", words[i]) != 1) {
words[i][0] = '\0'; // If line was all white-sapce
}
puts(words[i]);
}

关于C fscanf 复杂格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46410441/

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