I wrote the following code to judge whether an expression entered by user has correct sequence of brackets or not, e.g. if user enters [a*(b+c)] its ok. But if he enters [a*(b+c)[ its not correct.
Stacklist.cpp is a file which contains the linked list implementation of stacks and definitions of functions of push and pop. Display is the function which just shows the top entry.
#include<iostream>
#include<exception>
using namespace std;
#include"stacklist.cpp"
int main()
{
string s;
cin>>s;//user inputs the string
stacklist<int> stack1;//the class in stacklist.cpp...int because all bracket's ascii values are ints
char c;
while((c=cin.get())!=EOF)
{
switch('c')
{
case '(': case '{': case '[':
stack1.push('c');
break;
case ')':
{char s=stack1.display();
try
{
if(s=='(')
{ stack1.pop();
continue;}
else
throw 5;
}//try block
catch(5) //.......(a)
{
cout<<"unmatched bracket error";
exit(-1);
}//catch over
}//')' case
break;
case '}': //.......(b)
{char s=stack1.display();
try
{
if(s=='{')
{ stack1.pop();
continue;}
else
throw 6;
}//try block
catch(6) //......(a)
{
cout<<"unmatched bracket error";
exit(-1);
}//catch over
}//'}' case
break;
case ']': ........(c)
{char s=stack1.display();
try
{
if(s==']')
{ stack1.pop();
continue;}
else
throw 7;
}//try block
catch(7) //.............(a)
{
cout<<"unmatched bracket error";
exit(-1);
}//catch over
}//']' case
break;//..........(d)
default:
break;
} //switch
} //while
if(stack1.display==0)//0 is displayed if stack is empty
cout<<"string is correct"<<endl;
else
cout<<"unequal number of brackets"<<endl;
system("pause"); //........(e)
return 0;
} //main
Now the problem is that when I compiled the code there were various errors:
syntax error before numeric constant.........in all (a)
case label '}' not within switch statement........(b)
case label ']' not within switch statement........(c)
syntax error before break.................(d)
ISO forbids declaration of 'system' with no type...........(e)
Please tell me how to plug these errors?
system is found in the header cstdio, but you did not #include that header.
Anyway, it's best not to use "tricks" like system("pause") to keep the console window after your program ends: if your console environment is not hanging around after your program has finished doing its meaningful work, then that's your console environment's fault/problem and you should configure it properly so that that does not happen. Pausing is not part of your program's job.
Catching looks like this:
catch (Type object-name) { code }
object-name is optional, but Type is not.
Therefore catch (6) is ill-formed. The other errors are a result of this one: parsing of your program goes all wonky when you write stuff that is not valid C++!
And your indentation is pretty horrendous.
C++ cannot catch a 5, but C++ can catch an int. Change all instances of catch(5) to catch(int) and that will solve that issue.
Also, on line 60, the ..... isn't commented, and in several places you compare string s to '{' chars instead of "{" strings.
Also, Tomalak Geret'kal noted that you have to #include <cstdlib> for the system and exit calls.
Related
case 4:
{char password[5],passwordr[]="bene";
printf("\nWhats your password? :");
fgets(password,5,stdin);
if(strcmp(password,passwordr)==0){
printf("Hello");
}
else{
printf("good buy!");
}
}
break;
I have the problem that this code doesn't work. All other cases from the switch statmante work very well. The problem ist, that I can not write some text with fgets. The compiler automatically jumps to the else statement. At the storage for passwort there ist only "\n".
I was working on a program with a simple switch function, so far it has always worked for me.
But this time I have a problem with the scanf function before the switch.
I honestly don't understand where the error may be.
This is the code:
#include <stdio.h>
#include <stdlib.h>
int main () {
int utente;
while(1) {
printf("Benvenuto, premere:\n");
printf("1) AZIONE 1\n");
printf("2) AZIONE 2\n");
printf("3) AZIONE 3\n");
printf("4) AZIONE 4\n");
printf("5) AZIONE 5\n");
printf("6) AZIONE 6\n");
scanf ("%d\n",&utente);
switch(utente) {
case 1: {
printf("AZIONE 1\n");
break;
}
case 2:{
printf("AZIONE 2\n");
break;
}
case 3: {
printf("AZIONE 3\n");
break;
}
case 4: {
printf("AZIONE 4\n");
break;
}
case 5: {
printf("AZIONE 5\n");
break;
}
return 0
I can't understand the return. After the scanf he asks me for another input to enter the switch. otherwise it does not enter. In the case of while, I repeat the cycle with a delay output on the houses. And it's an extremely easy program. I don't know if it is a problem of the switch or the scanf.
Please help.
A whitepace character (space, newline, tab, etc) in scanf's format string means it'll ignore any number of whitespaces in the input. So when you hit ENTER (which sends a newline character), it'll be ignored regardless of how many you send. In order to terminate this directive, you have to input a non-whitepace character.
From C11 standard:
A directive composed of white-space character(s) is executed by
reading input up to the first non-white-space character (which remains
unread), or until no more characters can be read. The directive never
fails.
That's what you observe here.
The solution is to remove the \n from the format string.
Note that scanf is generally error prone for user inputs and is hard to use correctly (see what happens if you input a non integer, such as a, to your program).
See Why does everyone say not to use scanf? What should I use instead?
because of new line '\n', in the scanf statement, after format specifier(%d), you were facing trouble.
Sorry for the vague title but i really do not know how to describe the problem concisely..and the following is the simple codes:
#include <iostream>
using namespace std;
bool func(int a,char c,int b,int& result)
{
switch(c)
{
case '-':
result=a-b;
break;
case '+':
result=a+b;
break;
default:
return false;
}
return true;
}
int main()
{
cout<<"Usage:A {+|-} B"<<endl;
while(true)
{
int a,b,result;
char c;
cin>>a>>c>>b;
if(func(a,c,b,result))
{
cout<<result<<endl;
}
else
{
cout<<"Input Error!"<<endl;
}
}
return 0;
}
The right method to use the program is to input A {+|-} B.
For example,you can input 1[SPACE]+[SPACE]2[ENTER](which I mean "1 + 2" and then press ENTER) then it will spit out "3" for me.For the purpose of making the program more robust,I try to input 1[SPACE]+[SPACE]2[SPACE]+[ENTER] It just give me many "2" printed on the shell.Is there anyone who could tell me how to fix the bug?Many thanks!
PS:The codes is available at github:bug0x001.cpp
You fail to check if the input was read correctly. That's the first thing to do in a robust program. Also, if it failed, you should fix the input source. The endless stream of 2 is caused by a broken cin.
if( cin>>a>>c>>b &&
func(a,c,b,result))
{
}
else
{
cin.reset();
}
Your problem is that you are trying to get ints and char with cin, this is ok if you need that exact input, but crash when reading strange things (like a letter as int), as it reads garbage
The best solution (for me) is to read everything as a string (check cin.getline and stuff like that), then you "parse" the input as you whant, for example:
if you read "19+ 32 3" you can "easily" eliminate all spaces and split by any non numeric symbol, getting 3 strings: s1="19",s2="+" and s3="323", then you just parse each string as int (or whatever you need) and the symbol as char or whatever.
If you find anythng weird, you can try to understand it, eliminate it or just show an input error.
Is more complex than doing a cin.reset after testing, but allow you to "understand" more types of data input
I want to have a menu display that accepts user input. However, I want the user to be able to go back to the beginning of the menu to reselect options.
while(end != 1) {
display menu options
prompt user for input
if(input == x) {
do this
}
else
do that
}
then, i want it to skip back up to the beginning of the loop and ask the question over again. Howcan I do this without creating an infinite loop of the menu printing across the screen?
Unfortunately you didn't really show the code you are using but rather some pseudo code. Thus, it is hard to tell what you are actually trying to do. From the description of your problem and your pseudo code I suspect, however, that the root of the problem is that you don't check your inputs and don't restore the stream to a reasonably good state! To read the menu selection you probably want to use code akin to this:
int choice(0);
if (std::cin >> choice) {
deal with the choice of the menu here
}
else if (std::cin.eof()) {
// we failed because there is no further input: bail out!
return;
}
else {
std::string line;
std::cin.clear();
if (std::getline(std::cin, line)) {
std::cout << "the line '" << line << "' couldn't be procssed (ignored)\n";
}
else {
throw std::runtime_error("this place should never be reached! giving up");
}
}
This is just a rough layout of how the input would basically look like. It would probably be encapsulated into a function (in which case you'd want to bail out of from a closed input somewhat differently, possibly using an exception or a special return value). The main part of his is to
restore the stream back to good state using std::isteam::clear()
skip over the bad input, in this case using std::getline() with a std::string; you could also just std::istream::ignore() the remainder of the line
There may be other problems with your menu but without seeing concrete code I'd think it is hard to tell what the concrete problems are.
Instead of using a while, consider using a function, so you can call it where you need it:
void f()
{
if(end != 1) {
display menu options
prompt user for input
if(input == x) {
do this
f();
}
else{
do that
f();
}
}
}
I am not sure what your looking for either but this is some rough code of a menu
while(1){
cout<<"******* Menu ********\n";
cout<<"-- Selections Below --\n\n";
cout<<"1) Choice 1\n";
cout<<"2) Choice 2\n";
cout<<"3) Choice 3\n";
cout<<"4) Choice 4\n";
cout<<"5) Exit\n";
cout<<"Enter your choice (1,2,3,4, or 5): ";
cin>>choice;
cin.ignore();
switch(choice){
case 1 :
// Code for whatever you need here
break;
case 2 :
// Code for whatever you need here
break;
case 3 :
// Code for whatever you need here
break;
case 4 :
// Code for whatever you need here
break;
case 5 :
return 0;
}
what i'm writing is simple, well, it should be, but i'm getting this error and i don't know what else to do, my code look like this
int main()
{
char *option;
while(strcmp(option,"exit")!=0){
int opt = GetSystemDefaultUILanguage();
std::string lang;
switch(opt)
{
case 3082:
lang = "number 3082";
break;
case 1033:
lang = "number 1033";
break;
}
std::cout<<lang<<'\n';
std::cin>>option;
}
}
when i compile it there isn't errors, but when i run it, i get a this error
Project xxxx raised exception class EAccessViolation with message 'Access violation at address zzzzz'.Process stopped. Use Step or Run to continue.
EDITED:
This is my full code, now is more simple, but still the same result.
even if i try with an if/else statement it wont work, need some help here, thanks
Your program will always get an access violation because of the following lines:
char *option;
while(strcmp(option,"exit")!=0){
std::cin>>option;
You never initialize the pointer option, but then try to use it. Change your code to this:
int main()
{
std::string option;
while(option != "exit")
{
int opt = GetSystemDefaultUILanguage();
std::string lang;
switch(opt)
{
case 3082:
lang = "number 3082";
break;
case 1033:
lang = "number 1033";
break;
}
std::cout<<lang<<std::endl;
std::cin>>option;
}
}
I can't tell you the cause of the specific run-time error you're seeing, but I call tell you what's wrong with your program: hardcoded paths to user directories. Localized names are just one of a myriad of things that can go wrong with trying to guess the paths yourself.
DON'T DO THAT. Instead, read environment variables or call Shell APIs to find out where this particular user wants temporary data stored (or documents, pictures, desktop icons, etc).
Have a look at getenv("TEMP") and ShGetSpecialFolderPath
Your problem is this line:
std::cin>>option;
The variable option is declared as an uninitialized pointer to a character. Thus in the above statement, you are reading data into an unknown location.
Why do you use C style strings (char *) and C++ std::string?
You should get rid of C style strings (unless they are constant).
Try this:
#include <iostream>
#include <string>
int main(void)
{
std::string option;
do
{
std::cout << "Type exit to end program." << std::endl; // endl will flush output buffer
std::getline(cin, option); // Input a text line into "option".
} while (option != "exit"); // C-style string, used as a constant.
return 0;
}
You wrote
BlockquoteProject xxxx raised exception class EAccessViolation with message 'Access violation at address zzzzz'.Process stopped. Use Step or Run to continue.
So why don't you pause your program before crash, go to the location and put a breakpoint? If you still can't cope with that than upload your code to a filesharing server and give us the link ;)