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".
Related
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.
I'm at the start of writing a csv-file parser for a file with around 8000 Ids. When running, after around half the Ids are read and printed, the Clion console starts overwriting the first outputs so that at the end of running the first Id in my consoles output is the 2626th instead of the first. What in my code is responsible for this?
When printing every read character before the switch starts, the output is complete. It also works with a smaller amount of Ids, when i shorten the amount in the csv to around 6000.
int main() {
string buffer;
char zeichen;
ifstream eingabe;
eingabe.open("../lib/Daten.csv");
int zustand=0;//0=Token, 1=Werte
if(eingabe){
while(!eingabe.eof()) {
eingabe.get(zeichen);
//cout<<zeichen; // with only this it works
switch(zeichen){
case';':
if(zustand==0){
cout<<"Token: "<<buffer<<"; ";
}
else if(zustand==1){
cout<<"Wert: "<<buffer<<"; ";
}
buffer="";
break;
case'\n':
if(zustand==0){
zustand=1;
cout<<"Token: "<<buffer<<endl;
}
else if(zustand==1){
cout<<"Wert: "<<buffer<<endl;
}
buffer="";
break;
default:
buffer+=zeichen;
break;
}
}
}
eingabe.close();
return 0;
}
Answered by all the helpful people in the comments. It seems to be connected to Clion
I am looking for help with my task, i need get character string from user until he push '.' or enter? I have no idea how to get individual char using cin or even getch()? Please guys help me !
We can use std::cin.get() to get a single char.
std::vector<char> input;
for(bool key = false; !key;)
{
char keyPressed = std::cin.get();
switch(keyPressed)
{
case '.':
case '\n':
key = true;
break;
default:
input.append(keyPressed);
break;
}
}
Using a switch statement like above, we can sort out periods and newlines from the rest, making the loop exit when we hit one.
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 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.