gpt4 book ai didi

c - 使用strtok解析数据

转载 作者:行者123 更新时间:2023-11-30 15:55:36 27 4
gpt4 key购买 nike

我有一行数据

211L    CRYST1   60.970   60.970   97.140   90.000   90.000  120.000  P 32 2 1         6

我想用 C 进行解析。具体来说,我想将 P 32 2 1 提取为单个字符串。

当我使用 strtok 时,它使用所有空格作为分隔符,返回各个字符串

P
32
2
1

问题的更简洁的措辞:

如果我有可变数量的字符串(在本例中为 4 个),如何将它们连接成单个字符串?

到目前为止我的代码:

while (fgets(line,sizeof line, PDBlist)!=NULL)
{
p=0;
pch=strtok(line,"\t");
sprintf(space[p],"%s",pch);

while(pch!=NULL){
pch=strtok(NULL," ");
p++;
sprintf(space[p],"%s",pch);

}

for(i=8;i<(p-1);i++){

if(i==(p-2))printf("%s\n",space[i]);
else printf("%s ",space[i]);

} }*

最佳答案

如果行的格式始终如发布的示例所示,则使用 strtok() 的替代方法是 sscanf() 。它为行内容提供一定程度的验证,无需额外编码(例如,验证 float 值):

const char* input = "211L    CRYST1   ....";
char first_token[32];
char second_token[32];
float float_1, float_2, float_3, float_4, float_5, float_6;
char last_token[32];

/* The '%31s' means read next sequence of non-whitespace characters
but don't read anymore than 31. 31 is used to leave space
for terminating NULL character.

'%f' is for reading a float.

'%31[^\n]' means read next sequence of characters up to newline
but don't read anymore than 31. */
if (9 == sscanf(input, "%31s %31s %f %f %f %f %f %f %31[^\n]",
first_token,
second_token,
&float_1,
&float_2,
&float_3,
&float_4,
&float_5,
&float_6,
last_token))
{
/* Successfully read 9 tokens. */
}

查看在线演示:http://ideone.com/To4ZP .

关于c - 使用strtok解析数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11941825/

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