2016-03-15 97 views
-2

這是我主要功能的一部分,問題是:如果我的翻譯輸入被給予多個單詞,程序無法正常工作,那麼我該如何解決這個問題?如何拆分字符串輸入?

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); 
    } 
    ... 
+0

它甚至不會編譯。 –

+0

這不是完整的程序,只是問題所在的部分。該程序編譯 –

+0

您必須向我們發送一個編譯的代碼,所以我們確信我們得到了同樣的問題,然後您就可以做到這一點。 – Matriac

回答

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; 
}