2013-03-01 1 views
0

다항식에서 coeffecients 및 지수의 값을 추출하려고합니다. 나는 이미 strtok을 사용하여 계수들을 추출하는데 성공했다. 지수를 찾기 위해 같은 개념을 적용했지만, strtok을 사용하여 구분 기호 뒤에 문자열을 추출하거나 첫 번째 문자를 건너 뛰는 방법을 모르며, 내가 알고있는 유일한 추출 도구는 strtok입니다.C 문자열을 사용하여 다항식 C++에서 지수를 추출하십시오.

이이 함수가 COEFF를 추출하는 것입니다

#include <iostream> 
#include <cctype> 
#include <cstring> 
#include <cstdlib> 
#include <string> 
using namespace std; 

void extractCoeff (char *str, char *copy); 
void extractExp (char *str, char *copy); 
int main() 
{ 
    const int SIZE = 150; // size for string input 

    char *string; 
    string = new char[SIZE]; 
    cout << "Enter the polynomial\n"<<"minus sign must not have a blank with a coeff"; 
    cin.ignore(); 
    cin.getline(string, SIZE); // input string example: -4x^0 + x^1 + 4x^3 -3x^4 

    char *copy1; 
    copy1 = new char[SIZE]; 
    strcpy(copy1, string); 
    extractCoeff(string, copy1); 

    cout << endl << endl; 
    char *copy2; 
    copy2 = new char[SIZE]; 
    strcpy(copy2, string); 
    extractExp(string, copy2); 


    return 0; 
} 

주요 기능을이다

void extractCoeff (char *str, char *copy) 
{ 
    char *p = strtok(str, " +"); // extract the first time 
    char *search; 
    int counter = 0; 
    while (p) 
    { 
     search = strstr(p, "x^"); 
     cout << "Token: " << p << endl; 
     cout << "Search " << search << endl; 
     p = strtok(NULL, " +"); 
     counter++; 
    } 

    cout << copy << endl; 

    // find coeff 
    int *coefficient; 
    coefficient = new int[counter]; 

    p = strtok(copy, " +"); // extract the second time to find coeff 
    int a = 0; 
    while (p) 
    { 
     cout << "p: " << p << endl; 
     long coeff; 
     if (*p == 'x') 
     { 
      coeff = 1; 
     } 
     else if (*p == NULL) 
     { 
      coeff = 0; 
     } 
     else 
     { 
      char *endptr; 
      coeff = strtol(p, &endptr, 10); 
     } 
     coefficient[a] = coeff; 
     p = strtok(NULL, " +"); 
     a++; 
    } 

    for (int i = 0; i < counter; i++) 
     cout << coefficient[i] << endl; 
} 

이것은 (작동하지 않는) 지수

void extractCoeff (char *str, char *copy) 
{ 
    char *p = strtok(str, " +"); // extract the first time 
    char *search; 
    int counter = 0; 
    while (p) 
    { 
     search = strstr(p, "x^"); 
     cout << "Token: " << p << endl; 
     cout << "Search " << search << endl; 
     p = strtok(NULL, " +"); 
     counter++; 
    } 

    cout << copy << endl; 

    // find coeff 
    int *coefficient; 
    coefficient = new int[counter]; 

    p = strtok(copy, " +"); // extract the second time to find coeff 
    int a = 0; 
    while (p) 
    { 
     cout << "p: " << p << endl; 
     long coeff; 
     if (*p == 'x') 
     { 
      coeff = 1; 
     } 
     else if (*p == NULL) 
     { 
      coeff = 0; 
     } 
     else 
     { 
      char *endptr; 
      coeff = strtol(p, &endptr, 10); 
     } 
     coefficient[a] = coeff; 
     p = strtok(NULL, " +"); 
     a++; 
    } 

    for (int i = 0; i < counter; i++) 
     cout << coefficient[i] << endl; 
} 

void extractExp (char *str, char *copy) 
{ 
    char *p = strtok(str, " x^"); // extract the first time 
    //char *search; 
    int counter = 0; 
    while (p) 
    { 
     //search = strstr(p, "x^"); 
     //cout << "Token: " << p << endl; 
     //cout << "Search " << search << endl; 
     p = strtok(NULL, " x^"); 
     counter++; 
    } 

    cout << copy << endl; 

    // find coeff 
    int *exp; 
    exp = new int[counter]; 

    p = strtok(copy, " x^"); // extract the third time 
    int b = 0; 
    while (p) 
    { 
     cout << "p2: " << p << endl; 
     int expVal; 
     if (*p == NULL) 
     { 
      expVal = 0; 
     } 
     else 
     { 
      char *endptr; 
      expVal = strtol(p, &endptr, 10); 
     } 
     exp[b] = expVal; 
     p = strtok(NULL, " x^"); 
     b++; 
    } 

    for (int i = 0; i < counter; i++) 
     cout << exp[i] << endl; 
} 
+1

"작동하지 않는 방법"을 알려주십시오. 너는 무엇을 기대하니, 너는 무엇을 얻 느냐? – JoergB

+0

정규 표현식을 사용하여 전체 입력을 구문 분석하는 것이 더 좋은 방법 일 수 있습니다. 예를 들어 ['boost :: regex'] (http://www.boost.org/doc/libs/1_53_0/libs/regex/doc/html/index.html), 또는 새로운 C + +에서'std :: regex' +11 표준. –

답변

1
를 추출하는 기능입니다 (일)

문제는 strtok이 파괴적이라는 것입니다. 당신은 부분적으로 그것을 알고있는 것처럼 보입니다. 복사본에서 함수에서 두 번 사용할 수 있기를 바랍니다. 그러나 extractCoeff이 main으로 돌아 가면 string이 가리키는 C 문자열의 내용이 손상되므로 extractExp으로 전화하면 잘못 잘라진 문자열 두 개를 전달합니다.

C++에서 문자열 처리에는 std::string을 사용해야합니다. 당신이 문자열을 찾을 멤버 함수 find, find_first_offind_first_not_of을 사용할 수 있습니다 std::string, 당신이 찾고있는 원래의 문자열을 파괴없이 를 추출 substr를 사용하고 있습니다.

C 함수를 사용하여 C 문자열에서 유사한 작업을 수행 할 수 있지만 C 질문이 될 수 있습니다. (cout과 C++ 헤더를 사용하면 프로그램이 C 프로그램으로 유효하지 않게되지만, 그 외 모든 것은 C++이 아닌 순수한 C입니다.)

그런데 : strtok은 파싱하는 방법으로 배우는 것이 아닙니다. 문자열. 그것은 파괴적이며, 재진입 적으로 사용할 수 없으며 일부 플랫폼에서는 스레드로부터 안전하지 않습니다. 대체물에 대해 파괴적인 내부 파싱을 필요로하는 아주 좋은 이유가 없다면, 그것을 사용하거나 약간 더 나은 친족 (POSIX에서) strtok_r을 사용하지 마십시오.

+0

그리고 정규식? http://en.cppreference.com/w/cpp/regex – qPCR4vir

+0

@ Lam Nguyen 결정 : C 또는 C++. – qPCR4vir

+0

@ qPCR4vir regex는 프로덕션 코드에서 작업을 완료하는 데 더 좋은 도구 일 것입니다. 그러나 문자 시퀀스 작업을 배우지 않아야합니다. – JoergB

관련 문제