gpt4 book ai didi

c - 理解 strspn(const char *s, const char *accept) 函数

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

我正在编写一个程序,逐行读取文件以将单词和翻译分开。下面的代码有效。但是,我无法理解 /* separate word and translation */ 部分的 load_dictionary 函数实际上是如何工作的。 I ran it through **gdb** .

不清楚的地方:

  • p 行的输出
  • word = line + strspn(line, DELIMS) 之后输出 p wordstrspn 不应该读取到 DELIMS\t 并打印 - ants\t

文件:字典.txt

WORD    TRANSLATION

ants anttt
anti eti
ante soggy
anda eggs

函数:主要

 /* maximum number of characters for word to search */
#define WORD_MAX 256

/* maximum number of characters in line */
#ifndef LINE_MAX
#define LINE_MAX 2048
#endif

int main(int argc, char * argv[]) {
char word[WORD_MAX], * translation;
int len;

if (argc <= 1)
return 0; /* no dictionary specified */

/* load dictionary */
load_dictionary(argv[1]);
return 0;
}

功能:load_dictionary:- 读取字典文件

/* delimiter for dictionary */
#define DELIMS "\t"

unsigned void load_dictionary(const char * filename) {
FILE * pfile;
char line[LINE_MAX], * word, * translation;

/* ensure file can be opened */
if ( !(pfile = fopen(filename,"r")) )
return icount;

/* read lines */
while ( (fgets(line, LINE_MAX, pfile)) ) {
/* strip trailing newline */
int len = strlen(line);
if (len > 0 && line[len-1] == '\n') {
line[len-1] = '\0';
--len;
}

/* separate word and translation */
word = line + strspn(line, DELIMS);

if ( !word[0] )
continue; /* no word in line */
translation = word + strcspn(word, DELIMS);
*translation++ = '\0';
translation += strspn(translation, DELIMS);
}
}

最佳答案

strspn 将给出 DELIM

中存在的初始字符数

strcspn 将给出 DELIM

中的初始字符数

(参见 http://man7.org/linux/man-pages/man3/strspn.3.html)

所以代码的想法是使用简单的指针算法使 wordtranslation 指针指向输入中的第一个单词和输入中的第二个单词.此外,代码在第一个单词后添加了一个 NUL 终止符,使其看起来像两个字符串。

例子:

line: \t\t\t\tC++\0\t\t\tA programming language
^ ^ ^
| | |
| | translation points here
| |
| NUL added here
|
word points here

所以打印 wordtranslation 将给出:

C++
A programming language

带有附加注释的代码:

        word = line + strspn(line, DELIMS);  // Skip tabs, i.e. 
// make word point to the
// first character which is
// not a tab (aka \t)

if ( !word[0] )
continue; /* no word in line */

translation = word + strcspn(word, DELIMS); // Make translation point to the
// first character after word
// which is a tab (aka \t), i.e. it
// points to the character just after
// the first word in line



*translation++ = '\0'; // Add the NUL termination and
// increment translation

translation += strspn(translation, DELIMS); // Skip tabs, i.e.
// make translation point to the
// second word in line which is

关于c - 理解 strspn(const char *s, const char *accept) 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57767867/

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