Delimiter matching in c++ - segmentation fault (core dumped) [closed] - c++

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I keep getting the segmentation fault error when running my program. I have no clue what is wrong. I googled the error message, I just don't know what it means. Any help would be great!
#include<iostream>
#include <stack>
using namespace std;
bool delimiterMatching(char *file){
stack<char> x;
int count = 0;
char ch, onTop, check;
while(ch != '/n'){
ch = file[count];
if (ch == '(' || '[' || '{')
x.push(ch);
else if (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[50];
cout << "enter sentence: ";
cin >> test;
if (delimiterMatching(test))
cout << "success" << endl;
else
cout << "error" << endl;
return 1;
}

A segmentation fault means your program tried to access a memory address that isn't valid. Typically it means you dereferenced a dangling pointer or indexed past the end of an array.
In this case, it looks like the problem is your while(ch != '/n') line. It has two problems:
First, '/n' is not a valid character literal. You probably meant '\n', which represents a newline character.
Second, your string doesn't end with a newline character, because cin >> test reads one line and discards the newline at the end. Your loop will go past the end of the array and into whatever's after it in memory, trying to find a newline character, and eventually it'll reach a location that it can't access, causing a segmentation fault. You should be checking for '\0', which is the null character that actually marks the end of the string.
When I change the ch != '/n' to ch != '\0', the program doesn't crash.
It'd be easier and safer to use a std::string rather than a char[50], by the way.

You cant use such comparison
if (ch == '(' || '[' || '{')
Try
if (ch == '(' || ch== '[' || ch=='{')

Related

if statement not being implemented in c++ [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 months ago.
The community reviewed whether to reopen this question 9 months ago and left it closed:
Original close reason(s) were not resolved
Improve this question
It seems, the if statement is not being called in the given program. The output says it's a consonant even if the input is a vowel.
#include <iostream>
using namespace std;
int main() {
char input[1];
cout << "Enter an alphabet:\n";
cin >> input;
if (input == "a" || input == "e" || input == "i" || input == "o" || input == "u") {
cout << "It is a vowel";
}
else
cout << "It is a consonant";
return 0;
}
First of all you don't need to use an array. And on top of that you should use single quotes, so you should have something like this :
int main(){
cout<<"Enter an alphabet:\n";
char input;
cin>> input;
if (input=='a' || input=='e' || input=='i' || input=='o' || input=='u' ){
cout<<"It is a vowel";
}
else
cout<<"It is a consonant";
return 0;
}

terminate called after throwing an instance of 'std::out_of_range' what(): basic_string [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 4 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
string word;
int l,eFound,xFound;
l = word.size();
cout <<"Enter a word: ";
cin >> word;
for (l>0 ; word.at(l)!='x' || word.at(l)!='e'; l--)
if (word.at(l) == 'e'){
eFound = true;
}
else if (word.at(l) == 'x'){
xFound = true;
}
if (eFound == true && xFound == true){
cout << "Your word, "<<word<<", contains the character 'e'"<<"\n";
cout << "Your word, "<<word<<", contains the character 'x'";
}
if (eFound == true && xFound != true){
cout << "Your word, "<<word<<", contains the character 'e'";
}
if (xFound == true && eFound != true){
cout << "Your word, "<<word<<", contains the character 'x'";
}
I'm not sure what is going on I'm trying to use a for loop to detect either e or x in a input of some word. I've clicked on other pages with the same error but they have different codes and I don't really understand what is explained. So what is causing this error? I'm 2 weeks into my first programming class, sorry if I'm asking a dumb question.
The issue is that indexing of std::string starts from zero. Not from 1. So, word.at(l) will crash if l = word.size();.
You should change the statement to: l = word.size() - 1;.
Also, Change your loop condition to for (; l >= 0 ; l--)
Suggestion:
Please go for library functions:
Like this:
#include <iostream>
#include <string>
using namespace std;
int main() {
string word;
cout <<"Enter a word: ";
cin >> word;
bool eFound = word.find('e') != string::npos;
bool xFound = word.find('x') != string::npos;
if (eFound) {
cout << "Your word, "<<word<<", contains the character 'e'" << "\n";
}
if (xFound) {
cout << "Your word, "<<word<<", contains the character 'x'" << "\n";
}
return 0;
}

Boolean function always returning true [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I am taking a course on Udemy to learn C++, and I am following along with the professor.
This is the exact code that is being used in the class.
You pass in a letter, and it tells you whether or not it is a vowel. However, it is saying every letter is a vowel. For example, when I pass in 'b', it says it is a vowel.
Any clue?
#include <iostream>
#include <cmath>
using namespace std;
bool isVowel(char letter) {
if ((letter == 'a') || (letter == 'e') || (letter = 'i') ||
(letter = 'o') || (letter = 'u'))
return true;
else
return false;
}
int main() {
char let;
cout << "Enter a letter: ";
cin >> let;
if (isVowel(let))
cout << let << " is a vowel." << endl;
else
cout << let << " is a consonant." << endl;
return 0;
}
I get the same problem using both codeblocks and xcode.
Thanks
Here is the problem:
(letter = 'i') || (letter = 'o') || (letter = 'u'))
You should change it with the == in order to make the comparison. = is for assignation.
You are assigning a character to the variable letter, instead of comparing the variable and the character.
A good thing to notice is that the result of an assignation is always true if the assignation was succesful, false if the assignation was not succesful. That means in your code there are at least 3 "true" booleans: (letter = 'i'), (letter = 'o'), (letter = 'u'). These assignations were succesful, so in your if statement, they correspond to the boolean true.

How do I get out of this do-while loop? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm trying to create a program that intakes a string of characters, verifies it, then sorts it and prints it out.
I'm sure there is a glaring logic error in here somewhere, can someone help point it out? I've spent hours staring at my screen. I tried everything I know in my limited knowledge of C++, but I still can't get the thing working.
Anything you can offer will help me in some way, even if it's condescending.
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
void mySort(string &s);
int main()
{
string str;
char c;
bool invalid = true;
cout<<"Please enter some alphabetical characters:"<<endl;
cout<<"(* to end input): ";
do
{
getline(cin, str, '*');
for(int i = 0; i < str.length(); i++)
{
c = str.at(i);
}
if(! ( ( c >= 'a' && c <= 'z' ) || ( c >= 'A' && c <= 'Z' ) ) )
{
cout<<"Error!"<<endl;
}
else
{
(invalid==false);
cout<<"You entered: "<<str<<endl;
mySort(str);
}
} while(invalid==true);
system("PAUSE");
return(0);
}
void mySort(string &s)
{
sort(s.begin(), s.end());
cout<<"The string after sorting is: "<<s<<endl;
}
I'm almost sure the problem with the verification lies in this line:
if(! ( ( c >= 'a' && c <= 'z' ) || ( c >= 'A' && c <= 'Z' ) ) )
I'm sure my bools are wrong as well.
Anything, anything at all, I've wasted several hours of my life banging my head against the wall because of this.
You never set invalid to anything but true.
This line:
(invalid==false);
should be:
invalid = false;
The former version compares invalid to false, then throws away the result of the comparison. Nothing changes.
(invalid==false); Should be invalid=false;
First change:
(invalid == false);
invalid = false;
As others have said, you are not assigning the invalid variable correctly. You are also not validating the input string correctly, either. You loop through the entire string, and then validate only the last character seen, rather than validating each character while looping.
I would suggest re-writing the loop to get rid of the invalid variable and fix the validation, eg:
int main()
{
string str;
char c;
do
{
cout << "Please enter some alphabetical characters:" << endl;
cout << "(* to end input): ";
if (!getline(cin, str, '*'))
break;
if (str.empty())
cout << "You did not enter anything!" << endl;
else if (str.find_first_not_of("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") != string::npos)
cout << "Error! Bad input" << endl;
else
{
cout << "You entered: " << str << endl;
mySort(str);
break;
}
}
}
while (true);
system("PAUSE");
return 0;
}

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.