我试图从多项式中提取系数和指数的值。我已经成功地使用strtok
. 我应用相同的概念来查找指数,但我不知道如何strtok
在分隔符之后提取字符串或跳过第一个字符,并且strtok
是我知道的唯一提取工具。
这是主要功能
#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;
}