Need Help Using "Sort" Within My Program - c++

I have a simple program that lists input in order of precedence, checking only for operators and ranking them like so, "*/+-":
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int prec(char op)
{
if (op == '*' || op == '/') return 0;
return 1;
}
bool compareprec(char a, char b)
{
return prec(a) < prec(b);
}
int main()
{
char input[] = "+-/*";
cin >> input;
sort(input, input + 4, &compareprec);
cout << input;
}
I'm trying to implement it within a more complex program that uses stacks to check alpha numerical input and do an infix to postfix conversion, ranking something that looks like this: "9*9+9" into "9 9 9 * +". The more complex program is as follows:
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int prec(char op)
{
if (op == '*' || op == '/' || op == '+' || op == '-') return 0;
return 1;
}
bool compareprec(char a, char b)
{
return prec(a) < prec(b);
}
int main()
{
stack<char> s;
char input;
while (cin.get(input) && input != '\n')
{
if (isalnum(input))
cout << input << " ";
else if (input == '(')
s.push(input);
else if (input == ')')
{
while (!s.empty() && s.top() != '(')
{
cout << s.top() << " ";
s.pop();
}
if(!s.empty())
s.pop();
else
cout << "ERROR: No Matching ( \n";
}
else if (s.empty() && input == '*'|| input == '/'|| input == '+'|| input == '-')
{
sort(input, input + 4, &compareprec); // Error Begins Here?
s.push(input);
}
else if (input == '*'||input == '/'||input == '+'|| input =='-')
while (!s.empty())
{
sort(input, input + 4, &compareprec); // More Errors Here?
cout << s.top() << "\n ";
s.pop();
s.push(input);
}
}
while (!s.empty())
{
cout << s.top() << " ";
s.pop();
}
}
But I keep getting an error that says:
error: no matching function for call to 'sort(char&, int, bool (*)(char, char))'
error: no matching function for call to 'sort(char&, int, bool (*)(char, char))'
And I'm not sure why. I know it's probably something painfully obvious/silly but I can't figure it out. Any help would be appreciated. Thanks in advance!

sort expects something that can be iterated over.
Your working example has
char input[]
(an array of char)
Your non working example removes the array syntax and makes it a plain char
char input
When you attempt to do:
sort(input, input + 4, &compareprec)
In the working case, because you are providing an array, you're telling it to iterate from the beginning of input to 4 past the location. In the non-working case you're telling it to go from say 'a' to 'd' (which is 'a' + 4).

Why do you have to sort anything in the second example? You have maximally two operators you have to compare, one on the top of the stack and one in the input. Just use your compareprec-function and act accordingly based on the result.
And by the way, to make your code a little prettier, create a function:
bool is_operator(char s);
Almost forgot to tell you, the version of int prec(char a) in the second example is wrong, use the first one.

Related

infinite while-loop not displaying cout

#include <iostream>
int main()
{
char c;
int value{}, value2{};
while(true)
{
if(std::cin >> c)
{
if(c == '|') break;
else continue;
while(std::cin >> value >> value2)
{
std::cout << value << '\n' << value2 << std::endl;
}
}
}
}
Hello, I am trying to do here is take two integers as input in an infinite while-loop with a terminating char to exit the loop. Seems to work nice and dandy but then why is it that my output for my declarations isn't displaying? I am working through my reading material step-by-step to further my understanding, any help please greatly appreciated.
p.s
Further, I may try to make an exception to handle a minor detail, like using Z^ (ctrl+ Z) in my command line prompt window to exit as it's not accepting, thank you.
That is because you have
if(c == '|') break;
else continue;
in your code.
What this is doing is, if the value of c is equal to '|', the compiler gets outside the while loop and if value of c is not equal to '|', the compiler encounters continue, which makes it go back to the while (true) line.
The compiler never reaches the cout line.
The nuance with C++ and working with parsing integers may cause some headaches as its implementation is quite specific. But here is some code that fulfills what I may have been requesting.
#include <iostream>
#include <string>
int main()
{
char c;
int i = 0;
int value[2];
std::string text;
while(std::cin >> c)
{
if(c == ',' || c == '|')
{
value[i] = std::stoi(text);
text = "";
i++;
i = i%2;
if(i==0)
{
std::cout << value[0] << ' ' << value[1] << std::endl;
}
}
else
{
text = text + c;
}
if(c == '|') break;
}
return 0;
}
What needs to happen is a comma is required for parsing int values here.
I.E
User input: 123, (enter) 456,
There is also a way to implement without commas using getline. message for further details if curious.

Code keeps printing "1" when everything is correct

The code runs and all but it doesn't print out the vowels, but instead prints a "1".
#include <iostream>
#include <string>
using namespace std;
int countVowels(string sentence,int numVowels)
{
for(int i =0; i<sentence.length(); i++)
{
if((sentence[i]==('a'))||(sentence[i]==('e'))||(sentence[i]==('i'))||(sentence[i]==('o'))||(sentence[i]==('u'))||(sentence[i]==('A'))||(sentence[i]==('E'))||(sentence[i]==('I'))||(sentence[i]==('O'))||(sentence[i]==('U')))
numVowels=numVowels+1;
}
}
int main()
{
string sentence;
int numVowels = 0;
do{
cout << "Enter a sentence or q to quit: ";
cin >> ws;
getline(cin,sentence);
}
if(sentence == 'q'|| sentence == 'Q');
cout << "There are " << countVowels << " vowels in your sentence." << endl;
return 0;
}
The output should be like this:
Enter a sentence or a to quit: I like apples!
There are 4 vowels in your sentence, and 11 letters.
Enter a sentence or q to quit: q
Bye!
My problem:
Can someone explain to me why it keeps printing a "1", and my "if" statement where I am supposed to assign the hotkey "q" to exit the program isn't working. When I run the program I get an error at the if statement saying "no match for operators=="
I usually don't like just providing a full solution, but since your question shows you have made a good effort, here's how I would write it (well, not quite, I simplified a little to be more beginner friendly):
#include <algorithm>
#include <iostream>
#include <string>
bool isVowel(char c)
{
// A simple function that returns true if the character passed in matches
// any of the list of vowels, and returns false on any other input.
if ( 'a' == c ||
'e' == c ||
'i' == c ||
'o' == c ||
'u' == c ||
'A' == c ||
'E' == c ||
'I' == c ||
'O' == c ||
'U' == c) {
return true; // return true if it's a vowel
}
return false; // remember to return false if it isn't
}
std::size_t countVowels(std::string const& sentence)
{
// Use the standard count_if algorithm to loop over the string and count
// all characters that the predicate returns true for.
// Note that we return the resulting total.
return std::count_if(std::begin(sentence),
std::end (sentence),
isVowel);
}
int main() {
std::string sentence;
std::cout << "Please enter a sentence, or q to quit: ";
std::getline(std::cin, sentence);
if ( "q" == sentence ||
"Q" == sentence) {
// Quit if the user entered a string containing just a single letter q.
// Note we compare against a string literal, not a single character.
return 0;
}
// Call the counting function and print the result.
std::cout << "There are "
<< countVowels(sentence) // Call the function on the input.
<< " vowels in your sentence\n";
return 0;
}
Hopefully the comments make it all clear.
Now you might have been told that you can't use the standard algorithms (std::count_if), since part of the exercise seems to be to write that. Well I'll leave that to you. Your current version is close to correct, but remember to return the result. And you don't really need to pass in the numVowels count, just create that within the function, and remember to return it.

Segmentation fault and out of memory error with STL in C++ code

#include <iostream>
#include <string>
#include <stack>
using namespace std;
int main(void) {
// creating a stack of characters
std::stack<char> stk;
// exp will store the current read expression
string exp;
// number of tes cases
int test;
std:: cin >> test;
// 1st for loop to be run up to value of test.
// Added a few "cout"s for debugging for my own.
for(int i=1;i<=test;i++)
{
cout<<"into the loop\n";
getline (cin,exp);
cout<< "have read the expression";
std:: cout << exp;
int explength= exp.length();
cout << explength;
// this loop will run up to the length of the string
for(int j=0;j<explength;j++)
{ // if the read character is a small case char,print it
if(exp.at(j)>=97 && exp.at(j)<=122)
std::cout << exp.at(j);
// Handling special symbols
// high to low : (),/,*,-,+
else
{
if(exp.at(j)=='(')
stk.push('(');
else if (exp.at(j) == ')')
{
while (stk.top()!='(')
{
std::cout << stk.top();
stk.pop();
}
stk.pop();
}
else if (exp.at(j) == '^')
{
while (stk.top()!='^')
{
std::cout <<stk.top();
stk.pop();
}
stk.push('^');
}
else if (exp.at(j) == '/')
{
while (stk.top()!='/' || stk.top()!='^' )
{
std::cout << stk.top();
stk.pop();
}
stk.push('/');
}
else if (exp.at(j) == '*')
{
while (stk.top()!='*' || stk.top()!='/' || stk.top()!='^')
{
std::cout << stk.top();
stk.pop();
}
stk.push('*');
}
else if (exp.at(j) == '-')
{
while (stk.top()!='-' || stk.top()!='*' || stk.top()!='/' || stk.top()!='^')
{
std::cout << stk.top();
stk.pop();
}
stk.push('-');
}
else if (exp.at(j) == '+')
stk.push('+');
}
}
std::cout << endl;
}
return 0;
}
This code take "test " number of expressions,one by one, process each expression as string and output its RPN to the console. 1st for loop is to read "test" number of expressions and 2nd for loop contains the logic to process each string. As this is my 1st STL program this code might contain some stupid function calls.
I am trying to change the given number of expression to Reverse Polish Notation using the stack in C++ STL. When I run this code on Ideone, the code enters the 1st for loop but does not print expression read in " string exp".When I run this on my windows pc ( G++ compiler ) ,it does not print anything inside the 1st for loop. It sometimes gives Segmentation Fault and some time Out of memory signal on Ideone. Too frustrated. I tried debugging it with GDB but no use. Any help will be appreciated. The problem statement for which I have written this code is : http://www.spoj.com/problems/ONP/
EDIT1 : Priority is High : (),/,*,-,+ : Low

Delimiter matching simple program won't work

I have looked over this for hours it seems like. This program will compile, it just can't detect errors correctly. And for some reason it will work when I type in hey [) or hey {], etc. But it won't work for hey[) or hey{]. Obviously in all cases it should detect an error but for some reason the space after 'hey' makes a difference.
#include<iostream>
#include <stack>
using namespace std;
bool delimiterMatching(char *file){
stack<char> x;
int count = 0;
char ch, onTop, check;
while(ch != '\0'){
ch = file[count];
if (ch == '(' || ch == '[' || ch == '{')
x.push(ch);
else if (ch == ')' || ch == ']' || ch == '}') {
onTop == x.top();
x.pop();
if((ch==')' && onTop!='(') || (ch==']' && onTop!='[') || (ch=='}' &&
onTop!= '{'))
return false;
}
count++;
}
if (x.empty())
return true;
else
return false;
}
int main()
{
char *test = new char();
cout << "enter sentence: ";
cin >> test;
if (delimiterMatching(test))
cout << "success" << endl;
else
cout << "error" << endl;
return 1;
}
With cin >> test you don't get a whole sentence, but only a string until cin encounters whitespace. So if you type (hey ), thest would be (hey and the closing brace would only be read by the next >>, whereas (hey) would work as expected.
You have a second issue with your test allocation, which might be too short for reasonable input.
Change main() as follows:
char *test = new char[256]; // enough space. COnsider also string
cout << "enter sentence: ";
cin.getline(test, 256); // full line input.
...
You have also two nasty bugs in delimiterMatching().
First you use an uninitialized ch in your while condition. Either initialise ch to a non nul char, or use while (file[count]).
And did you notice onTop == x.top(); ? Shouldn't it be onTop = x.top();?

Using Stacks In C++ for infix and postfix expressions

I'm writing a program that takes user input and uses stacks to convert an infix expression into a postfix expression based on precedence, with operands always going before operators. For example, if a user inputs:
(a+b*c)
then the program should display:
abc*+
so far, I have this:
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int main()
{
stack<char> s;
char input;
while (cin.get(input) && input != '\n')
{
if (isalnum(input))
cout << input << "\n";
else if (input == '(')
s.push(input);
else if (input == ')')
{
while (!s.empty() && s.top() != '(')
{
cout << s.top();
s.pop();
}
if(!s.empty())
s.pop();
else
cout << "ERROR: No Matching ( \n";
}
else if (s.empty() && input == '*'||'/'||'+'||'-' && s.top() < input) // Error Begins Here?
{
char a = '*';
char b = '/';
char c = '+';
char d = '-';
bool prec (char a, char b, char c, char d);
return ('*' > '/' > '+' > '-');
s.push(input);
}
else if (input == '*'||'/'||'+'||'-' && s.top() >= input)
while (!s.empty())
{
cout << s.top();
s.pop();
s.push(input);
}
}
while (!s.empty())
{
cout << s.top();
s.pop();
}
}
Which compiles and runs but is not functioning as it should. When an expression like "ab" is input, the program will display "ab" as it should but if I input "a+b+c", then only "a" will be displayed. This means the program is not placing the operators into the stack to be displayed later on. What I need help with is modifying the program so that when an operator is input, it should be added onto the stack and then displayed based on it's precedence (*>/>+>-) after the operands, when the input is done.
I'm quite new to C++ and programming in general, so any suggestions would be great.
else if (input == '*'||'/'||'+'||'-' && s.top() >= input)
This does not do what you think it does. You need to do
else if (input == '*'|| input == '/'|| input == '+'|| input == '-' && s.top() >= input)
And this looks like an error too
bool prec (char a, char b, char c, char d);
That's the syntax for a function prototype. Are you sure this compiles?
The problem is here:
bool prec (char a, char b, char c, char d);
return ('*' > '/' > '+' > '-');
I'm guessing this is intended to define a precedence function, but that's not what it's doing. The first line declares that such a function exists (and its arguments have nothing to do with the variables declared in the previous lines), and the second causes the whole program to terminate. If you want a function like this, you must define it outside main.
A slightly less dramatic bug is here:
if (s.empty() && input == '*'||'/'||'+'||'-' && s.top() < input)
First, this part
input == '*'||'/'||'+'||'-'
is interpreted as
(input == '*') || ('/') || ('+') || ('-')
The last three terms are true, the first is irrelevant. And I'm not even sure what s.top() does if s is empty.
This should be enough to go on. I suggest you start by building and testing routines that can, e.g., identify the operators and evaluate their precedence, before you try putting everything together in one program.
Falmarri is right just wanted to post that my self , and it compiles I tried it , but there is another thing : you said
else if (s.empty() && input == '*'||'/'||'+'||'-' && s.top() < input) // Error Begins Here?
Are you sure that even reached that point because when I runn it , it just stops on the :
while (cin.get(input) && input != '\n')
until I hit enter and even more you can enter more then one char from consol while in cin.get(input) but the input will contain only the first char you entered . To solve this I just put an
#include <conio.h>at the beginning an used
while ((input = getch()) && input != (char)13) in staid of you're code
short explanation
getch()
returns after you press only one character and
input != (char)13
is required in staid of
input != '\n'
because getch() return (char)13 for ENTER see ASCII table for more info.