【问题标题】:Splitting a line array into words将线阵列拆分为单词
【发布时间】:2014-11-15 07:55:31
【问题描述】:

我有一个由一行单词组成的数组(我使用 fgets)。我现在想创建一个新数组作为包含相同行的同一结构的一部分,但拆分为只有字母数字字符的单词(这样 line[1].word_in[3] 会给我第 1 行中的第三个单词)。我尝试了一些,但没有成功。

    typedef struct {
        char linewords[101];
        char separateword[101];
    } line;

    line linenum[101];

    while fgets(linenum[i].linewords, 101, stdin) != NULL) {
        i++
        linenum[i].separateword = linenum[i].linewords.Split(' ');
        if (isalnum(int linenum[i].separateword) != 0) {
            /* need to remove that character */
        }
    }

我很抱歉我真的不知道我在做什么。我的第一个问题显然是拆分结构,因为这给了我一个错误。谢谢

编辑: 我已经添加了我现在正在做的事情;但是我在分配 var 时收到分配错误。

    typedef struct {
        char linewords[101];
        char separateword[101];
    } line;

    line linenum[101];
    char var[101]
    char *strtok(char *str, const char delim);

    while fgets(linenum[i].linewords, 101, stdin) != NULL) {

        char* strcopy();
        char* strtok();
        strcpy(linenum[i].separateword,linenum[i].linewords);
        strtok(linenum[i].separateword, ' '); /*this line causes seg fault*/
        i++
        }
    }

【问题讨论】:

  • 你说的没用是什么意思?
  • 我收到以下错误:“在非结构或联合中请求成员‘拆分’”。
  • linenum[i].linewords.Split(' ') 你不能这样编造语法。如果您打算使用 C,然后了解 C,您就不能期望在一种语言中工作的任何东西都能神奇地在另一种语言中工作。
  • C 没有函数 .Split 像 c# 一样尝试不同的东西。
  • 你没听懂我说的。无论是变量还是结构的孩子,你仍然不能使用“var.split”。 C 不允许这样做。

标签: c arrays struct


【解决方案1】:

strtok() 返回一个字符指针。它在

char *strtok(char *s, const char *delim) ;

所以问题是你没有保存返回的值。

while fgets(linenum[i].linewords, 101, stdin) != NULL) {

        //strcpy(linenum[i].separateword,linenum[i].linewords);
        linenum[i].seperatewords=strtok(linenum[i].linewords, ' ');
        i++
        }

它会解决你的问题。 有关 strtok() 的更多详细信息: strtok()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-13
    • 2011-11-03
    • 2016-01-30
    • 1970-01-01
    • 1970-01-01
    • 2019-11-24
    • 2019-03-12
    相关资源
    最近更新 更多