There is no red line under the code. When I start without debugging, after I entered the email, a failure is popped up, "abort() has been called". How can I debug this?
#include <iostream>
#include <string>
using namespace std;
int main() {
string email;
bool good = false;
while (good == false)
{
there:
cout << "Email is ";
cin.ignore();
getline(cin, email);
cout << email.length();
int a;
for (int q = 0; q <= email.length(); q++)
{
char x = email.at(q);
int count = 0;
while (x == '#')
{
a = 1;
count++;
}
if (count > 1)
{
a = 0;
}
}
if ((email.at(0) == '#') || (email.at(email.length()) == '#') || (a == 0))
{
cout << "Input is invalid. One character ‘#’ must be found. Moreover, there must be some characters before and after the character ‘#’." << endl;
goto there;
}
else
{
good = true;
}
}
}
I see a lot of problems in your code. First check my comment for one about your for-loop.
Next, in your for loop, you while-loop will be an infinite loop if the first character is indeed '#', as you would never break out of it.
while (x == '#')
{
a = 1;
count++;
}
Related
I'm trying to take user inputted notes and store them in an array. The validation works fine but when I input the last value in the loop I get:
Debug Assertion Failed!
Expression: "(_Ptr_user & (_BIG_ALLOCATION_ALIGNMENT - 1))==0"&&0
An invalid parameter was passed to a function that considers invalid parameters fatal.
I'm struggling to understand where the issue is and how I can fix it.
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
typedef string noteName;
noteName getNoteName(int i)
{
bool flag = true;
noteName Namein;
do
{
cout << "Please enter note name no. " << i + 1 << ": ";
cin >> Namein;
cout << "------------------------------------\n";
if (Namein.length() > 3 || Namein.length() < 2)
{
cout << "Sorry, a note name must be 2 or 3 characters long. Please try again.\n";
flag = false;
}
else if (Namein.length() == 3 && Namein[1] != '#')
{
cout << "Sorry, the second character of a sharp note name must be #. Please try again.\n";
flag = false;
}
else if ((Namein[0] < 'a' || Namein[0] > 'g') && (Namein[0] < 'A' || Namein[0] > 'G'))
{
cout << "Sorry, the first character of a note name must be a letter between A and G. Please try again.\n";
flag = false;
}
else if (isdigit(Namein.back()) == false)
{
cout << "Sorry, the last character of a note name must be a number. Please try again.\n";
flag = false;
}
else
{
flag = true;
}
} while (flag == false);
return Namein;
}
int main()
{
const int numNotes = 4;
noteName NoteNames[numNotes];
cout << "Hello\n";
for (int i = 0; i <= numNotes; i++)
{
NoteNames[i] = getNoteName(i);
}
cout << "Thank you, the note names and lengths you entered were: \n\n";
for (int i = 0; i <= numNotes; i++)
{
cout << i << ". " << NoteNames[i] << "\n";
}
cout << "Done!";
return 0;
}
I want to say it's something to do with getNoteName() having a string return type as I haven't had this issue with any of my other functions that return int.
noteName NoteNames[numNotes]; defines an array where NoteNames[numNotes - 1] is the largest element you can access.
You go one further than this. The behaviour on doing that is undefined which is manifesting itself as the crash that you observe.
Replace your loop limits with for (int i = 0; i < numNotes; i++), or similar.
(You also have your CamelCase conventions for class names and variable names switch round from what's normal, which makes your code confusing to read.)
(I'd also rather see constexpr int numNotes = 4;: Google that for more details.)
I'm aware that there's already stuff here regarding this but I'm just posting to check if my logic lines up with my code (if I'm thinking about this whole infix Postfix thing the way I should be).
The code I've seen regarding this topic on this site look a little different from mine. I'm kind of a novice at C++. Anyway, my code so far looks like it is just fine and should work just fine but it's not working the way it should. I've included my thought process as comments in the code below. Please let me know if what I'm thinking is okay.
Here's the code:
#include <iostream>
#include <stack>
#include <sstream>
#include <string>
using namespace std;
int priority (string item)
{
int prior = 0;
if (item == "(")
{
prior = 1;
}
if ((item == "+") || (item == "-"))
{
prior = 2;
}
else if ((item == "*") || (item == "/"))
{
prior = 3;
}
else
{
prior = 4;
}
return prior;
}
int main()
{
stack<string> st;
string output;
cout << "Welcome. This program will calculate any arithmetic expression you enter" << endl;
cout << "Please enter an arithmetic expression below: " << endl;
char line[256];
cin.getline(line, 256);
string exp;
exp = line;
cout << "This is the expression you entered: ";
cout << exp << endl;
string item;
istringstream iss(exp);
iss >> item;
// While there are still items in the expression...
while ( iss )
{
// If the item is a number
if (isdigit('item') == true)
{
output = output + " " + item;
}
// If the stack is empty
else if (st.size() == 0)
{
st.push(item);
}
// If the item is not a number
else if (isdigit('item') == false)
{
// convert that item in the expression to a string
atoi(item.c_str());
int prior1 = 0;
int prior2 = 0;
// If that string is a LEFT PARENTHESIS
if (item == "(")
{
st.push(item);
}
// If that string is a RIGHT PARENTHESIS
else if (item == ")")
{
while ((st.empty() == false) && (st.top() != "("))
{
output = st.top() + " ";
st.pop();
}
st.pop();
}
else
{
// store what is returned from "priority" in "prior1"
prior1 = priority(item);
// pass item on top of the stack through "priority"
// store that in "prior2;
prior2 = priority(st.top());
// while loop here, while item has a higher priority...
// store numbers in a variable
while (prior1 > prior2)
{
output = output + " " + st.top();
st.pop();
prior2 = priority(st.top());
}
}
}
}
while (st.empty() == false)
{
output = st.top() + " ";
st.pop();
}
cout << "Here's the postfix: " << output << endl;
}
This is for evaluating postfix to an actual answer:
// EVALUATE POSTFIX
stack<int> st2;
string output2;
istringstream iss2(exp);
iss2 >> item;
while (iss)
{
// If the item is a number
if (isdigit('item') == true)
{
st.push(item);
}
if (isdigit('item') == false)
{
// store item in a variable
// pop another item off the stack
// store that in a variable.
// apply operator to both.
// push answer to the top of the stack.
int m = 0;
int n = 0;
int total = 0;
m = st2.top();
st2.pop();
n = st2.top();
st2.pop();
if (item == "+")
{
total = m + n;
st2.push(total);
}
else if (item == "-")
{
total = m - n;
st2.push(total);
// add the thing you popped of the stack with the first thing on the stack
}
else if (item == "*")
{
total = m * n;
st2.push(total);
}
else if (item == "/")
{
total = m / n;
st2.push(total);
}
}
}
cout << "Here's your answer: " << st2.top() << endl;
}
Am I thinking about this whole infix-postfix thing the way I should be? Am I on track to solving this problem? My apologies if this question seems simple. I'm kind of a novice at this. Thank you very much.
#include <iostream>
#include <string>
#include <queue>
#include <stack>
#include "NodeType.h"
using namespace std;
// Test if token is an operator
bool isOperator(char token);
int getPrecedence(char token);
bool comparePrecedence(char tokenA, char tokenB);
int main()
{
stack<char> tokenStack;
queue<char> tokenQueue;
string expression= "", postfix= "";
char x;
cout<<"Please enter a mathematical expression: "<<endl;
getline(cin, expression);
cout<<expression.length()<<endl;
for(int i = 0; i <= expression.length(); i++)
{
x = expression[i];
if(isdigit(x))
{
tokenQueue.push(x);
}
if(isOperator(x))
{
while((!tokenStack.empty()) && (comparePrecedence(x, tokenStack.top() == true)))
{
char z = tokenStack.top();
tokenQueue.push(z);
tokenStack.pop();
}
tokenStack.push(x);
}
if(x == '(')
{
tokenStack.push(x);
}
if(x == ')')
{
while((!tokenStack.empty()) && (tokenStack.top() != '('))
{
char z = tokenStack.top();
tokenQueue.push(z);
tokenStack.pop();
}
tokenStack.pop();
}
while(!tokenStack.empty())
{
char z = tokenStack.top();
tokenQueue.push(z);
tokenStack.pop();
}
}
return 0;
}
int getPrecedence(char token)
{
if((token == '+') || (token == '-'))
{
return 1;
}
else if((token == '*') || (token == '/'))
{
return 2;
}
else if ((token == '(') || (token == ')'))
return 0;
else
return 99;
}
// Test if token is an operator
bool isOperator(char token)
{
return token == '+' || token == '-' ||
token == '*' || token == '/';
}
bool comparePrecedence(char tokenA, char tokenB)
{
if(getPrecedence(tokenA) < getPrecedence(tokenB))
return true;
else
return false;
}
For some reason I cannot get my code to work correctly. It always throws a
Thread 1: EXC_BAD_ACCESS (code=EXC_1386_GPFLT) error. It is also not correctly placing the '+' sign when I test using a simple string such as: (3+4).
The Queue should look like: 34+ but it hold 3+4. It seems to me that the '+' operator never gets pushed onto the stack. Can anyone please help me find what I should be focussing my attention on?
Debugging code is a valuable skill to learn, it's my opinion that it should form a much more important part of curricula in schools.
For example, if you modify your code to output all the stack and queue operations thus:
int main()
{
stack<char> tokenStack;
queue<char> tokenQueue;
string expression= "", postfix= "";
char x;
cout<<"Please enter a mathematical expression: "<<endl;
getline(cin, expression);
cout<<expression.length()<<endl;
for(int i = 0; i <= expression.length(); i++)
{
x = expression[i];
if(isdigit(x))
{
tokenQueue.push(x);
cout << "qpush A " << x << '\n';
}
if(isOperator(x))
{
while((!tokenStack.empty()) && (comparePrecedence(x, tokenStack.top() == true)))
{
char z = tokenStack.top();
tokenQueue.push(z);
cout << "spop G " << z << '\n';
cout << "qpush B " << z << '\n';
tokenStack.pop();
}
tokenStack.push(x);
cout << "spush E " << x << '\n';
}
if(x == '(')
{
tokenStack.push(x);
cout << "spush F " << x << '\n';
}
if(x == ')')
{
while((!tokenStack.empty()) && (tokenStack.top() != '('))
{
char z = tokenStack.top();
tokenQueue.push(z);
cout << "spop H " << z << '\n';
cout << "qpush C " << z << '\n';
tokenStack.pop();
}
cout << "spop I " << tokenStack.top() << '\n';
tokenStack.pop();
}
while(!tokenStack.empty())
{
char z = tokenStack.top();
tokenQueue.push(z);
cout << "spop J " << z << '\n';
cout << "qpush D " << z << '\n';
tokenStack.pop();
}
}
return 0;
}
and run it with a simple 3+4, you'll see the following output:
qpush A 3
spush E +
spop J +
qpush D +
qpush A 4
So you are placing the operation on the stack. However, you later take it off the stack and put it on the queue before you place the next digit on the queue.
That's definitely the wrong order but, if you examine the code, it's not just a small snippet that has two lines in the wrong order (that would be too easy).
The code that's doing that transfer from stack to queue is the final while loop in main() which, after every single character, transfers all the items from the stack to the queue, effectively rendering your stack superfluous.
That's where you should be looking but I'll give you a clue. You don't want to be transferring stack to queue after every character, only for those that involve numbers.
There may well be other problems after you solve that one but that method (debugging output every time you do something important) should be able to give you enough information to fix whatever comes along.
When I run my program, I have to type how many rows do I want in my output. I have a limit from 1 to 100 rows. Each row is a task with a name of the task followed by increasing number, example: Task1:, Task2, .... When I type something into input, it must convert input string /see the code below - except the code in main();/.
My problem is that when I type first input, it should go to next task/next row/ but it doesnt. I type for example 10 strings but they dont go each to next task but they stay in one task..hope you understand now.
#include<iostream>
#include<string>
#include <ctype.h>
using namespace std;
void Convert(string input){
string output = "";
string flag = "";
bool underscore = false;
bool uppercase = false;
if ( islower(input[0]) == false){
cout << "Error!" <<endl;
return;
}
for (int i=0; i < input.size(); i++){
if ( (isalpha( input[i] ) || (input[i]) == '_') == false){
cout << "Error!" <<endl;
return;
}
if (islower(input[i])){
if (underscore){
underscore = false;
output += toupper(input[i]);
}
else
output += input[i];
}
else if (isupper(input[i])){
if (flag == "C" || uppercase){
cout << "Error!"<<endl;
return;
}
flag = "Java";
output += '_';
output += tolower(input[i]);
}
else if (input[i] == '_'){
if (flag == "Java" || underscore){
cout << "Error!" <<endl;
return;
}
flag = "C";
underscore = true;
}
}
cout << output <<endl;
}
int main(){
const int max = 100;
string input;
int pocet_r;
cout << "Zadaj pocet uloh:" << endl;
cin >> pocet_r;
if(pocet_r >= 1 && pocet_r <=100)
{
for (int i = 0; i <pocet_r; i++)
{
cout << "Uloha " << i+1 << ":" << endl;
while (cin >> input)
Convert (input);
while(input.size() > max)
cout << "slovo musi mat minimalne 1 a maximalne 100 znakov" << endl;
while(input.size() > max)
cin >> input;
while (cin >> input)
Convert(input);
}
}else{
cout << "Minimalne 1 a maximalne 100 uloh" << endl;
}
system("pause");
}
Your first if in Convert will always fail on a non-underscore and return. I don't think that's what's intended. Agree with other answer on the while cin loop. The next two whiles should be if's apparently. Step thru this code with a debugger and watch it line by line and see where it fails. You've got multiple issues here, and I'm not entirely sure what the intent is.
Edit - I didn't parse the extra parenthesis correctly. The first if in convert is actually okay.
In this in the main function the usage of getchar in do while loop is creating problem (as per what i m figuring out) and using getch resolves it..plz help why so..
#include <iostream>
#include <cstring>
#include <stdio.h>
using namespace std;
const int size = 10;
int main()
{
int stack[size];
int top = -1;
char ch;
char chh;
do {
cout << "what you want to do? 1:Push,2:Pop,3:Display \n";
cin >> ch;
if (ch == '1')
{
int a;
cout << "enter element to be entered";
a = getchar();
int r = push(stack, &top, a);
if (r == -1) cout << "array already full \n";
}
if (ch == '2')
{
pop(stack, &top);
}
if (ch == '3')
{
display(stack, &top);
}
cout << "enter y to continue";
chh = getchar();
} while (chh == 'y');
return 0;
}
Some else clauses will help. Put all those if's into one big if/else if/else loop:
if (ch == '1') { ... }
else if (ch == '2') { ... }
else if (ch == '3') { ... }
else { /*print out the bad char*/ }
You're likely getting a character that you're not expecting, like a carriage return.
Also, why are you mixing cin and getc?