boboobobo
boboobobo

Reputation: 67

Invalid Conversion from char to string

In my code, I made a string and I pushed that string to a stack. (I don't know if I did it correctly as I am new to C++ and the concept of stacks) But when I try to top (I think this outputs the first element in the stack) it doesn't work correctly. I get a conversion issue from char to string. Even if I cast it as char it doesn't work correctly. Is there some way to convert it? I am trying to get it to out put h.

I keep getting the error :

C:\main.cpp:15:37: error: invalid user-defined conversion from 'char' to 'std::stack >::value_type&& {aka std::basic_string&&}' [-fpermissive] nextWord.push(str[i + 1]);

#include <iostream>
#include <iomanip>
#include <map>
#include <string.h>
#include <stack>

using namespace std;

int main(){
std::stack<string> nextWord;
string str = "T<h>is is a test";

for(int i = 0; i < str.length(); i++){
    if (str[i + 2] == '>' && str[i] ==  '<'){
        nextWord.push(str[i + 1]);
    }
}
while (!nextWord.empty()) {
    cout << "String: " << nextWord.top();;
}

cout << nextWord.pop() << '>' ;
}

Upvotes: 0

Views: 2312

Answers (3)

Evgeniy331
Evgeniy331

Reputation: 414

In you code 3 problems:

  1. nextWord.push(str[i+1]); You try to put char in the stack instead string. You need change the type of stack: stack<char> nextWord; or convert char to string before putting in the stack for example:

        string tmp = "";
    
        tmp += str[i+1];
    
        nextWord.push(tmp);
    
  2. Endless cycle:

        while (!nextWord.empty()) {
         cout << "String: " << nextWord.top();
        }
    

    stack.top() - just returns value in the top of the stack

    to pass all the elements you need add calling stack.pop() in the body of cycle, for example:

        while (!nextWord.empty()) {
            cout << "String: " << nextWord.top();
            nextWord.pop();
        }
    
  3. cout << nextWord.pop() << '>' ; The return type of the stack.pop() is void. You can not write like this.

Upvotes: 4

Dale
Dale

Reputation: 544

The problem is this line:

nextWord.push(str[i + 1]);

str[i + 1] is a char, and you're trying to push it onto a string stack. Change it to this, and it should work fine:

nextWord.push(string(1, str[i + 1]));

Upvotes: 1

AndersK
AndersK

Reputation: 36082

stack::pop has return value void. In order to get the value from the stack use top and then call pop.

cout << nextWord.top() << ">";
nextWord.pop();

When you push strings you need to push the string, not a character i.e.

nextWord.push(str);

Also #include <string> instead of string.h

Upvotes: 1

Related Questions