[英]C fscanf complex format
我正在尝试从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
我想阅读第一 , 第二 , 第三 , 第四四个单词,其余的将被丢弃。 我有此问题的解决方案,但我不明白为什么会这样:
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");
}
输入文件应采用特殊格式。
对于格式字符串的不同组成部分,它们如何工作以及整个解决方案为何起作用的解释,我将不胜感激。
(我也找不到有关fscanf格式工作方式的任何特定信息,如果有人可以给我参考,我会很高兴的)
在通常情况下,“以及为什么整个解决方案行得通”,IMO则没有。
2种fscanf(in, ...
格式中的第二个'\\n'
使其成为较弱的解决方案。 '\\n'
将扫描任意数量的换行符和任何空格。最好继续使用fgets(string, ...)
,然后sscanf(string, ...)
"%255s[^\\n]\\n"
在[
"%255s"
之后寻找[
。 奇怪的代码。 @约翰·布林格
代替
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]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.