如何拆分字符串输入?

时间:2016-03-15 17:59:13

标签: c

这是我的主要功能的一部分,问题是:如果我的翻译输入被赋予多个单词,程序无法正常工作,任何关于如何解决这个问题的想法?

int main() {
    struct node *temp;
    char str[1000];
    char word[MAXP];
    char translation[MAXT];
    char option[15];

    while (1) {
        str[0] = '\0';
        word[0] = '\0';
        translation[0] = '\0';

        scanf("%[^\n]%*c", str);
        sscanf(str, "%s %s %s", option, word, translation);
    }
    ...

1 个答案:

答案 0 :(得分:1)

您可以使用fgets来阅读每个输入。然后sscanf扫描前两个子字符串。使用%n说明符,可以捕获扫描的字符数,以允许您使用该索引中的strcpy。

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

int main()
{
    char end = '\0';
    char str[1000];
    char word[1000];
    char translation[1000];
    char option[15];
    int used = 0;
    int scanned = 0;

    while(1){

        str[0]='\0';
        word[0]='\0';
        translation[0]='\0';

        fgets ( str, sizeof ( str), stdin);
        str[strcspn ( str, "\n")] = '\0';//remove newline
        scanned = sscanf(str, "%14s%999s%c%n", option, word, &end, &used);
        if ( scanned >= 1) {//one sub string scanned
            printf ( "%s\n", option);
        }
        if ( scanned >= 2) {//two sub strings scanned
            printf ( "%s\n", word);
        }
        if ( scanned == 3) {//two sub strins and a character scanned
            strcpy ( translation, &str[used]);
            printf ( "%s\n", translation);
        }
    }
    return 0;
}