0

文字列に文字を 1 つずつ追加しようとしています。私はこのようなものを持っています:

void doline(char *line, char *buffer, char** tokens){
}

そして私はそれを次のように呼んでいます:

char *line = malloc(1025 * sizeof(char *));
fgets(line, 1024, stdin);
int linelength = strlen(line);
if (line[linelength - 1] == '\n'){
    line[linelength - 1] = '\0';
}

char ** tokens = (char **) malloc(strlen(line) * sizeof(char *));
char *emptybuffer = malloc(strlen(line) * sizeof(char *));

parseline(line, emptybuffer, tokens);

そのため、dolineは行を調べて、さまざまな条件に基づいてトークン化し、そのフラグメントをトークンに配置します。変数バッファーに一時文字列を作成しています。これを行うには、文字ごとにをたどる必要があります。

私は現在やっています:

buffer[strlen(buffer)] = line[i];

そして、ループの最後に:

*buffer++ = '\0';

しかし、これは結果です:

printf("Working on line: '%s' %d\n", line, strlen(line));

出力: 行での作業: 'test' 4

しかし、関数の終わりまでにバッファは次のようになります。

*buffer++ = '\0';
printf("Buffer at the very end: '%s' %d\n", buffer, strlen(buffer));

出力: 最後のバッファ: 'test' 7

そのため、出力は文字列がめちゃくちゃになっていることを示しています。この文字列を文字ごとに作成する最良の方法は何ですか? 私の文字列操作は正しいですか?

どんな助けでも大歓迎です!

ありがとう!

4

1 に答える 1

1

基本的な問題がいくつかあったので、プログラムを書き直しました。

#include <stdio.h>
#include <stdlib.h>

#define str_len 180

void tokenize(char *str, char **tokens)
{
    int length = 0, index = 0;
    int i = 0;
    int str_i;
    int tok_i;

    while(str[length]) {
        if (str[length] == ' ') {
            /* this charecter is a space, so skip it! */
            length++;
            index++;

            tokens[i] = malloc(sizeof(char) * index);

            tok_i = 0;           
            for (str_i=length-index ; str_i<length; str_i++) {
                tokens[i][tok_i] = str[str_i];
                tok_i++;
            }

            tokens[i][tok_i] = '\0';
            i++;
            index = 0;
        }
        length++;
        index++;
    }       

    /* copy the last word in the string */
    tokens[i] = malloc(sizeof(char) * index);
    tok_i = 0;           
    for (str_i=length-index ; str_i<length; str_i++) {
        tokens[i][tok_i] = str[str_i];
        tok_i++;
    }
    tokens[i][tok_i] = '\0';
    tokens[i++] = NULL;

    return;         
}

int main()
{
    char *str = malloc(str_len * sizeof(char));
    char **tokens = malloc(100 * sizeof(char *));
    int i = 0;

    if (str == NULL || tokens == NULL)
        return 1;

    gets(str);
    printf("input string: %s\n", str);
    tokenize(str, tokens);

    while(tokens[i] != NULL) {
        printf("%d - %s \n", i, tokens[i]);
        i++;
    }

    while(tokens[i])
        free(tokens[i]);
    free(tokens);
    free(str);

    return 0;
}

次のようにコンパイルおよび実行されます。

$ gcc -ggdb -Wall prog.c 
$ ./a.out 
this is a test string... hello world!! 
input string: this is a test string... hello world!! 
0 - this  
1 - is  
2 - a  
3 - test  
4 - string...  
5 - hello  
6 - world!!  
$ 

基本的な仮定はほとんどありませんでした。

  1. 着信文字列の長さは定数と見なされます。これは動的に行うことができます - これを確認してください - How to read a line from the console in C? .

  2. tokens 配列の長さも定数であると見なされます。これも変更可能です。方法を見つけるためにそれをあなたに任せます!

お役に立てれば!

于 2012-04-25T04:07:34.160 に答える