Strtok 和 String 操作问题 [英] Strtok and String manipulation issues

查看:30
本文介绍了Strtok 和 String 操作问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#define DELIMS "!\"#$%&()|'*+,?/:;<=>@[\092]^_{}~\177" 

void getFileLine(FILE *fp)
{

    char *word, *ptr;
    int tokennum, count;
    char buffer[100];


    while(!feof(fp))
    {
        (fgets(buffer, 100, fp));
        ptr = buffer;
        for(tokennum = 1; word = strtok(ptr, DELIMS);ptr = NULL, tokennum++)
        {
            word = strtok(ptr, DELIMS);
            printf("%s\n", word);
        }
    }
}

所以我传入了一个包含示例程序的文件.我的工作是删除一些 delim 并将代码中的每个单词传递到树中.

So I am passing in a file that has a sample program in it. My job is to remove some delims and pass each word from the code into a tree.

虽然我不在树部分,只是致力于按照我想要的方式操作字符串,但我遇到了一些问题.

While I am not at the tree part and just working on getting the strings manipulated the way I want, I am having some issues.

因此,当我从 .txt 文件中读取行时,我得到了我想要的一部分..txt 中的前几行如下:

So, as I read the lines from the .txt file, I am getting part of what I want. The first couple of lines from the .txt is as follows:

#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define FLUSH while( getchar()!= '\n')

现在,在它运行我的代码后,它变成了:

Now, after it runs through my code, it turns it into:

include
include
include
include
define FLUSH while

"<> 中的单词被删除,因为它们是一些 delims.我遇到的问题是在 define FLUSH while 部分.当一行多个单词不是 delim 时,我希望每个单词单独显示,从而输出:

The words in " and <> are removed because those are a few of the delims. The problem I am having is at the define FLUSH while part. When a line as more than one word that is not a delim, I want each word to be displayed separately, making the output:

include
include
include
include
define
FLUSH
while

如您所见,define FLUSH while 现在将每个单词都放在单独的行上.

As you can see, the define FLUSH while now has each word on a separate line.

我认为使 ptr=NULL 会导致 strtok 重复使用该行直到它到达末尾,但我再次在完成此操作时遇到了一些麻烦.任何建议/帮助都会很棒.谢谢.

I thought making ptr=NULL would cause the strtok to reuse the line until it reached the end, but again I am having a little trouble getting this done. Any advice/help would be great. Thanks.

推荐答案

问题在于您定义 for 循环的方式:

The issue is the way you have defined your for loop:

以下是代码的简化片段:

Here is a simplified snippet of the code:

for (; word = strtok(ptr, DELIMS);ptr = NULL)
{
    word = strtok(ptr, DELIMS);
    printf("%s\n", word);
}

这相当于:

while(word = strtok(ptr, DELIMS))
{
    word = strtok(ptr, DELIMS);
    printf("%s\n", word);
    ptr = NULL;
}

注意你如何在每次迭代中调用 strtok 两次,但只打印一次?这意味着您将丢失所有其他令牌.

Notice how you call strtok twice in each iteration, but only print once? This means you will lose every other token.

此外,您还没有将 (space) 添加到您的令牌列表中,因此它不会在空格上拆分.

Furthermore, you haven't added (space) to your list of tokens, so it won't split on spaces.

这篇关于Strtok 和 String 操作问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆