문제

Im trying to make one mix string based on others two, for example, string1 = "Good Morning" and string2 = "Hello guys", So my script will output like that: "Good Hello Morning guys".

I have almost done it.. what i tried:

int main() {
  char frase1[99];
  char frase2[99];
  int i =0;
  char frase3[99];

  printf("Type a sentence: ");
  gets(frase1);
  printf("Type a sentence: ");
  gets(frase2);

  char * pch1;
  char * pch2;

  pch1 = strtok (frase1," ");
  pch2 = strtok (frase2," ");

  while (pch1) {
    strcat(frase3,pch1); 
    pch1 = strtok (NULL, " ");

    strcat(frase3,pch2); 
    pch2 = strtok (NULL, " ");
  }
  puts(frase3);
}

output: Example: frase1 = "Good morning"; frase2 = "Hey guys"; output: error

도움이 되었습니까?

해결책 2

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

int main() {
    char frase1[99];
    char frase2[100] = {' '};
    char frase3[sizeof(frase1)+sizeof(frase2)];

    printf("Type a sentence: ");
    scanf("%98[^\n]", frase1);
    printf("Type a sentence: ");
    scanf(" %98[^\n]", frase2+1);

    char *pch1, *pch2, *pch3;
    int len1, len2;

    pch1 = frase1;
    pch2 = frase2;
    pch3 = frase3;

    while (*pch1 || *pch2) {
        if(*pch1){
            sscanf(pch1, "%*s%n", &len1);
            memcpy(pch3, pch1, len1);
            pch1 += len1;
            pch3 += len1;
        }
        if(*pch2){
            sscanf(pch2, "%*s%n", &len2);
            memcpy(pch3, pch2, len2);
            pch2 += len2;
            pch3 += len2;
        }
    }
    *pch3 = '\0';
    puts(frase3);
    return 0;
}

다른 팁

Your problem is quite simple:

  1. strtok is not psychic and has no idea you wanted to resume the earlier token sequence, and not the one it labored on last.
  2. It will only return NULL wen it cannot return a token, you test for that too late.

Take the replacement-function strtok_s (optional C99 #define __STDC_WANT_LIB_EXT1__ 1) or strtok_r (POSIX), which is reentrant because it does not use any static internal storage.
If you can do neither, save the first sequence and then get the second one.

Next problem will be having a different number of tokens in both sentences.

The final problem you will run into (if frase1 and frase2 are long enough) is overflowing frase3: That should be at least as long as both combined.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top