Pregunta

This is the homework that I encounter problem, given line of string and need to store into a list of array

Here is how I declare the list of array

list<terms> poly[100];

And here is my struct data type

typedef struct Node*terms;
struct Node
{
    int expo;       //exponent
    int coef;       //coefficient
}

Given:

string line = "123456"

I need to get the first two characters at a time and store to a struct(terms in this case) Data type so I save '1' as token and '2' as token2. Also I need them to be int data type for later calculation. After saving them into new terms, it will loop again and read '3' and '4', convert them and save again, etc.

I've tried to use stringstream to convert but it gave me invalid conversion from char' to const char*

for ( string::iterator it=line.begin(); it!=line.end(); it++){

    int token, token2;

    //change data type from string to int
    stringstream ss;
    ss<<*it;
    ss >>token;

    stringstream ss;
    ss<<*it+1;
    ss >>token2;

    //create a new struct for current line
    struct Node* p = (struct Node*) malloc(sizeof(struct Node));
    p->coef = token;
    p->expo = token2;
    poly[0].push_back(p);
}
¿Fue útil?

Solución

For example you can use an ordinary loop.

std::pair<int, int> p;

for ( std::string::size_type i = 0; i < line.size(); i++ )
{
   if ( i & 1 == 0 )
   {
      p.first = line[i] - '0';
   }
   else
   {
      p.second = line[i] - '0';
      poly[0].push_back( new Node { p.first, p.second } );
   }
}

Only it is not clear why you defined the list as std::list<Node *> instead of std::list<Node> You could write simply

      poly[0].push_back( { p.first, p.second } );
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top