a problem in the stack
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
|
#include <iostream>
#include <string>
#include <stack>
using namespace std;
stack<string> A;
string str ("ilove*youtube*cplusplus");
void stock(string&str)
{ int i=0;
while(i<str.size())
{
if(str.at(i)=='*')
{
A.push(str.at(i+1));
}
else
A.push(str.at(i));
i++;//endif
}//end while
while (!A.empty())
{
cout << " " << A.top();
A.pop();
}
}
int main()
{
stock(str);
system("pause");
return 0;
}
|
I got the result 16 C:\Dev-Cpp\main.cpp invalid conversion from `char' to `const char*'
And I'm wondering why.
I think it's because you're trying to push chars onto a stack of strings; try making the stack one of chars instead and see what happens.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
|
#include <iostream>
#include <string>
#include <stack>
using namespace std;
stack<char> A;
string str ("ilove*youtube*cplusplus");
void stock(string&str)
{ int i=0;
while(i<str.size())
{
if(str.at(i)=='*')
{
A.push(str.at(i+1));
}
else
A.push(str.at(i));
i++;//endif
}//end while
while (!A.empty())
{
cout << " " << A.top();
A.pop();
}
}
int main()
{
stock(str);
system("pause");
return 0;
}
|
It works but it is inverse.
how to output iloveyoutubecplusplus?
What do you want? Do you want to remove symbol '*' from the string or you want to use the stack for such an operation?
Last edited on
It works but it is inverse. |
Stack is LIFO (Last In First Out), so if you enter
1 2 3
, output will be
3 2 1
.
Push characters starting from the end:
1 2 3 4 5
|
for(int i = str.size() - 1; i>=0; --i) {
if(str.at(i)=='*')
continue;
A.push(str.at[i])
}
|
By the way this code
1 2 3 4 5 6 7 8 9 10 11
|
while(i<str.size())
{
if(str.at(i)=='*')
{
A.push(str.at(i+1));
}
else
A.push(str.at(i));
i++;//endif
}//end while
|
has bugs.
Consider for example a string that contains string literal "*" or "**" or even "*A"
yes, i notice that, thanks for your advise.
Topic archived. No new replies allowed.