Reputation: 67
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
Reputation: 414
In you code 3 problems:
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);
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();
}
cout << nextWord.pop() << '>' ;
The return type of the stack.pop() is void. You can not write like this.
Upvotes: 4
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
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