wrong input will exit the program c++ - c++

So I have started to learn c++ and I have wrote this simple program , when a user inputs wrong number it gives an option to try again however when a user inputs any characters it gives the option to try again and directly exits the program why is that happening ?
`
#include<unistd.h>
#include<stdio.h>
int main(){
int a;
char b ,c;
start:
printf("INPUT ONLY NUMBER 1 : ");
scanf(" %d", &a);
if(a==1)
{
printf( " you entered correctly \n");
printf("do you want to try again? <Y> <N> \n");
scanf(" %c", &c);
if(c=='Y' ||c=='y')
{
goto start;
}
}
else {
sleep (1);
printf("wrong number , do you want to try again? <Y> <N> \n");
scanf(" %c" , &b);
}
if (b=='Y'||b=='y')
{
sleep(1);
goto start;
}
else
if(b=='n'||b=='N')
{
sleep(1);
printf("thank you and goodbye");
exit (1);
}
}
`

scanf(" %d")
I bet your problem comes from that space before the %d. Try scanf("%d"). Same later: scanf("%c") instead of scanf(" %c ").
Anyway, your code is VERY dirty. And this looks like C, not C++.
Not trying to be a maniac here, but you should indent properly and AVOID the goto BY ALL MEANS. Your program structure is simple and a while loop will do the trick for you. You should also avoid to explicitly call exit(1). exit is mostly used to provoke premature termination. In your case, your program reaches its end normally, and you should exit with your main function's return 0.
#include <unistd.h>
#include <stdio.h>
#include <stdbool.h> //Reauired to use boolean type in C
int main()
{
bool stop = false; //boolean type only has two states: true and false. Very useful for loops!
while(!stop) //Read as "While we don't need to stop, execute the loop's contents
{ //Much easier to read!
printf("INPUT ONLY NUMBER 1 : ");
scanf("%d", &a);
if(a == 1)
{
printf("you entered correctly \n");
printf("do you want to try again? <Y> <N>\n");
scanf("%c", &c);
if(c == 'N' || c == 'n')
{ //We only need to tell the loop when to stop
stop = true; //by setting stop to true
} //The loop's default behavior is to loop execution of its content
}
else
{
sleep(1);
printf("wrong number , do you want to try again? <Y> <N> \n");
scanf("%c" , &b);
if(b=='n'|| b=='N')
{
stop = true; //Same as above
}
sleep(1);
}
}
printf("thank you and goodbye");
return 0;
}

There is something left behind from your scanf, which sometimes you can clean that up flushing it, but in your code seems not to work.
Having a look at that issue this comes across:
http://c-faq.com/stdio/stdinflush2.html
Which basically tells you that if your approach does not work, then you should change it.
Hope this help, you also asked about while in one of your questions there, so:
#include <iostream>
int main(){
char input;
char try_again;
do {
std::cout << "INPUT ONLY NUMBER:";
std::cin >> input;
// http://en.cppreference.com/w/cpp/string/byte/isdigit
// does not return a bool, you can check that >0
if (std::isdigit(input)) {
// do what you want.
std::cout << "digit\n";
continue;
} else {
// you can as for more imput like:
std::cout << "Not a number, try again?(y/Y):";
std::cin >> try_again;
std::tolower(try_again);
if (try_again == 'y') {
continue; // will start the loop again.
} else {
break; // it will exit the loop.
}
}
} while(true);
return 0;
}

Related

How to stop input in this code- a code to input an 1D array with unknown size

I try to do this but i don't know how to stop input. I build a code with input an array with integer element, when input element not integer, it will ignore. So i can't stop it.
do {
if(std::cin >> val) {
if(val == 0) break;
vec.push_back(val);
} else {
std::cin.clear();
std::cin.ignore(1,'\n');
}
} while(true);
I try to enter ctrl + x,z,d but it don't work.
You can decide to stop input on end of file. The condition is raised on actual end of file when you read from a true file, or but using Ctrl Z or F6 on Windows or Ctrl D on Linux. You just have to test for it before ignoring any offending input:
do {
if(std::cin >> val) {
if(val == 0) break;
vec.push_back(val);
} else if (std::cin.eof()) {
break; // exit loop on eof
} else {
std::cin.clear(); // ignore any offending input up to end of line
std::cin.ignore(1,'\n');
}
} while(true);

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.

My little self made application closes instantly

I have written this little piece in C++ and if I open the program it should sum up the input then the "Press to finish" should be printed, and after it is printed the application should close after the user enters 'Enter'. The problem is it closes itself already after the numbers added are added.
#include <stdlib.h>
#include <stdio.h>
int multi(int a, int b){
return a * b;
}
int main(){
printf("Programm started \n");
int number1;
int number2;
int sum;
printf("Type two numbers: \n");
scanf("%d %d", &number1, &number2);
sum = multi(number1,number2);
printf("The solution is: %d \n", sum);
printf("Press <Return> to finish \n");
char c = getchar();
if(c=='\n'){
return 0;
}
}
I don't see you waiting for the user to hit enter:
char c = getchar(); // get the next available character
// If there is one then take it
// This only waits if there is no input available.
// This does nothing.
// If the character is '\n' it returns 0
// but if it is not the '\n character then you immediately exit
// In C++ if main does not have a final return the compiler plants
// a return 0 autoamtically so it also returns zero.
if(c=='\n'){
return 0;
}
// implied return 0 here
So if I look at your other code:
scanf("%d %d", &number1, &number2);
This reads two numbers from the input. BUT it does not read the new line character. This means you still have a new line character left on the input stream which is why the getchar() at the end is returning immediately.
Change:
scanf("%d %d\n", &number1, &number2);
// ^ Specifically read a newline here.
//
// Be careful.
// This is not a perfect solution. If there are any other characters
// after your numbers this will fail (so you really should do some more
// and better processing but this will resolve your immediate problem).
//
// I would add a loop here (just after you read your numbers)
// to read and discard any junk on this line (or read and error
// if there is junk but be OK if the only input is white space
// terminated by a new line).
When you press enter in scanf("%d %d", &number1, &number2); the new line character is going to be read by getchar and hence (c=='\n') is true.
what you could do is ignore that new line left by scanf like this :
char c = getchar();
if (c == '\n') c = getchar();
if (c == '\n') {
return 0;
}
If you print the value of c as an unsigned integer,
printf("%u\n",c);
then you'll see that it already has a value of 10 which is a newline. getchar returns the next character from the standard input which means you still have a newline character on the input stream from your previous scanf calls.
scanf("%d %d\n", &number1, &number2);
will specifically read in that hanging new line.
scanf only reads your two inputs from the input buffer and leaves the '\n' when you enter the first two numbers and hit enter, which later on is ready by getchar().
To read a line including spaces, do not use scanf("%s",....) Consider fgets().
fgets(string, sizeof string, stdin);
// remove potential trailing \r\n as needed
string[strcspn(string, "\n")] = 0;
Alternatively you could use %*c. Check the live code here.
int main(){
printf("Program started \n");
int number1;
int number2;
int sum;
printf("Type two numbers: \n");
scanf("%d %d%*c", &number1, &number2); // Add %*c here
sum = multi(number1,number2);
printf("The solution is: %d \n", sum);
printf("Press <Return> to finish \n");
char c = getchar();
printf("c: %c", c);
if(c=='\n'){
printf("hi");
return 0;
}
}
%*c will accept but ignore any following characters.
If you were using i/o streams then this works.
#include<iostream>
int main()
{
int dummy = 0;
std::cout << "Enter A number to exit" << std::endl;
std::cin >> dummy;
return 0;
}
Keeps the window open until you enter something, anything will do.

While-loop breaks, and I don't know the reason why

I was writing a code for a counter. If I give 'a' as input, it should +1 the counter and show it on the screen. But when I do it, it shows 1 on the screen and the program ends. I want it to run until and unless i give some other character as input. What's the mistake I am making?
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
int Counter = 0;
char t;
while(true)
{
t = cin.get();
if(t == 97)
{
Counter = Counter + 1;
}
else
break;
system("cls");
cout << Counter;
}
return 0;
}
The issue is when you are entering your 'a', you are probably hitting Enter as well, which is interpreted as another char. That second char is definitely not a, so your program breaks. This can be verified by just outputting what you read:
for (;;) {
std::cout << '?';
char t = std::cin.get();
std::cout << (int)t << '\n';
if (t != 'a') break;
}
std::cout << "done\n";
Which, when run, prints:
?a
97 // this is 'a'
?10 // this is '\n', note the additional ?
done
The simplest fix would be to use the input stream operator on cin, which would discard whitespace in the input (whereas get() does not):
char t;
for (;;) {
std::cout << '?';
std::cin >> t;
std::cout << (int)t << '\n';
if (t != 'a') break;
}
std::cout << "done\n";
Which, when run, produces:
?a
97
?b
98
done
which is what you'd intended.
Try this:
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
int Counter = 0;
char t;
while(true)
{
t = cin.get();
if(t == 97)
{
Counter = Counter + 1;
}
// else
// break;
system("cls");
cout << Counter;
}
//system("pause");
return 0;
}
Your else break; is the reason why you're closing after any interation. Basically after any iteration, it will break because due to any non-a input. However, running the code above, you will see the counter increment at every a input given and it will not break.
This will give you the basic operation you're looking for which is increment the counter based on input a, otherwise do nothing.
Edit: The above code will buffer your input and read it all, so if you have 5 a's like the following aaaaa, it will read it and output 5 for the counter.
If you want to break out of the loop, i suggest this:
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
int Counter = 0;
char t;
while(true)
{
cin >> t;
// t = cin.get();
if(t == 97)
{
Counter = Counter + 1;
}
else
break;
system("cls");
cout << Counter;
}
//system("pause");
return 0;
}
I tested it and it works. Seems to be with how cin.get() reads the buffered input from the console (i think). Not too sure on the specifics, but cin >> t does the trick.
Edit 2: Did some reading and i think cin.get() will consume the next character after your input, but in this case it is a newspace \n, which is why it will always break in your original code.

Project1.exe has stopped working for no reason (C++)

I have a C++ code in dev C++ where all of the sudden it just says project 1.exe has stopped working and i dont know why
#include <iostream>
using namespace std;
int main()
{
char *upasscode;
char *spasscode;
spasscode = ("FISH");
cout<<"ENTER PASWWORD\n";
cout<<"--------------\n";
cin>> upasscode;
if ( upasscode != spasscode ) {
goto incorrect;
}
else {
goto correct;
}
incorrect:
cout<<"INCORRECT";
system("pause>null");
system("EXIT");
correct:
cout<<"Welcome!";
system("pause>null");
system("EXIT");
}
One issue is that your incorrect code flows into your correct code, there is nothing to change the path of execution.
If you like goto, I suggest the following:
incorrect:
cout<<"INCORRECT";
system("pause>null");
system("EXIT");
goto end_of_program;
correct:
cout<<"Welcome!";
system("pause>null");
system("EXIT");
end_of_program:
return 0;
Or you could simplify:
incorrect:
cout<<"INCORRECT";
goto end_of_program;
correct:
cout<<"Welcome!";
end_of_program:
system("pause>null");
return 0;
Alas, probably something better:
int main()
{
char *upasscode;
char *spasscode;
spasscode = ("FISH");
cout<<"ENTER PASWWORD\n";
cout<<"--------------\n";
cin>> upasscode;
if ( upasscode != spasscode )
{
cout << "INCORRECT\n";
}
else
{
cout << "Welcome!\n";
}
system("pause>null");
return EXIT_SUCCESS;
}
Do you really need the system("EXIT") function call or will a return (exit) from main suffice?
cin >> upasscode;
upasscode is a char* that does not have memory allocated to it. When you extract input into upasscode you will be dereferencing addresses that you do not own, thus Undefined Behavior.
Instead you can use std::string which will dynamically-resize itself to accommodate extra characters.
std::string spasscode;
std::cin >> spasscode;
Moreover, you're using goto which is a very bad programming practice. You can always restructure your program in a better way than that.