infinite loop in c++ [duplicate] - c++

This question already has answers here:
Infinite loop with cin when typing string while a number is expected
(4 answers)
Closed 3 years ago.
I'm learning C++ and writing little programs as I go along. The following is one such program:
// This program is intended to take any integer and convert to the
// corresponding signed char.
#include <iostream>
int main()
{
signed char sch = 0;
int n = 0;
while(true){
std::cin >> n;
sch = n;
std::cout << n << " --> " << sch << std::endl;
}
}
When I run this program and keep inputs at reasonably small absolute values, it behaves as expected. But when I enter larger inputs, e.g., 10000000000, the program repetitively spits out the same output. Some combinations of input cause erratic behavior. For example:
#: ./int2ch
10
10 -->
10000000000
10 -->
10 -->
10 -->
10 -->
The program spits out "10 --> " until it's killed. (With this particular sequence of inputs, the program's output changes speed erratically.) I also noticed that the output of large values is determined by the previous legal input as well as the value of the current illegal input.
What's going on? (I don't care about fixing the program, that's easy. I want to understand it.)

Basically your cin stream is in a fail state and thus returns immediately when you try to read it. Rewrite your example like this:
#include <iostream>
int main()
{
signed char sch = 0;
int n = 0;
while(std::cin >> n){
sch = n;
std::cout << n << " --> " << sch << std::endl;
}
}
cin >> n will return a reference to cin, which you can test for "good-ness" in a conditional. So basically the the "while(std::cin >> n)" is saying "while i could still read from standard input successfully, do the following"
EDIT: the reason it repeatedly output the last good value entered is because that was the last value successfully read in n, the failed reads won't change the value of n
EDIT: as noted in a comment, you can clear the error state and try again something like this would probably work and just ignore bad numbers:
#include <iostream>
#include <climits>
int main() {
signed char sch = 0;
int n = 0;
while(true) {
if(std::cin >> n) {
sch = n;
std::cout << n << " --> " << sch << std::endl;
} else {
std::cin.clear(); // clear error state
std::cin.ignore(INT_MAX, '\n'); // ignore this line we couldn't read it
}
}
}

Yes, Evan Teran pointed out most things already. One thing i want to add (since i cannot comment his comment yet :)) is that you must put the call to istream::clear before the call to istream::ignore. The reason is that istream::ignore likewise will just refuse to do anything if the stream is still in the fail state.

Given that you are on a 32 bit machine, 10000000000 is too big a number to be represented by an int. Also converting an int to a char will only give you from 0..255 or -128..127 depending on the compiler.

One problem here is that a char has a size of one byte, and thus can only hold a number between -127 and 128. An int on the other hand, is typically 4 bytes, and can take on much larger values. Second problem is that you are inputting a value that is too large even for an int.

Related

compare number elements in array of char

I am new to programming and I want to get an unlimited input of numbers from user, and I need to compare each number to 4 or 7; if the number is 4 or 7, I will increase counter.
The issue is that the if condition if(arr[i]!='4' || arr[i]!='7') is executed even if the number is 4 or 7.
I tried to implement another if by comparing ASCII code >>> if(arr[i]!=0x34 || arr[i]!=0x37) but this solution also doesn't work.
Can you help me to find the issue?
#include <iostream>
#include <string>
#include <string.h>
using namespace std;
int main()
{
int counter=0;
char arr[]={};
cin >> arr;
for (int i=0 ; i<strlen(arr)-1 ; i++)
{
if(arr[i]!='4' || arr[i]!='7')
{
cout << "NO" << endl;
counter=0;
break;
}else
counter++;
}
cout << counter << endl;
if(counter==4 || counter==7)
cout << "YES" << endl;
}
Your program has undefined behavior, because this
char arr[]={};
creates an array of length zero. This is not even allowed in standard C++. If your compiler didn't complain about it, then that is because it is using a non-standard language extension.
In any case, the array has length zero. You then try to write to it with
cin >> arr;
which causes the array to be accessed out-of-bounds, no matter how long the given input is. This will cause undefined behavior and you will not have any guarantee whatsoever on how the program will behave.
Never use char arrays to store strings, especially not user input. Use std::string instead:
std::string arr;
cin >> arr;
Then instead of strlen(arr) you should use arr.size().
I am pretty sure you have further logic errors in your program (see question comments). But before you fix the program logic, you should make sure that you are writing a valid program in the first place.

How to read unknown number of inputs?

I am learning C++ using the book C++ Primer.
In Section 1.4.3, the following example code about reading the unknown number of inputs is given.
#include <iostream>
int main()
{
int sum = 0, value = 0;
// read until end-of-file, calculating a running total of all values read
while (std::cin >> value)
sum += value; // equivalent to sum = sum + value
std::cout << "Sum is: " << sum << std::endl;
return 0;
}
According to the book, if we give an input of 3 4 5 6, the output will be Sum is: 18
But when I try this on my computer(Windows 10 with MinGW), The code does not end. It just keeps on asking for input even if I enter a newline. It works only when I enter a non-int input like f.
Is this expected? If yes, is there any code that stops after inputting a newline?
I am quite new to c++ and I have already learned python, so getting stuck so early on is quite frustrating.
Thanks and regards.
You need to terminate your input by an End-Of-File-character (i.e. CTRL-Z on Windows, CTRL-D on Mac/Unix), not just by an End-Of-Line (i.e. Enter).
A simple Enter is interpreted as white space, which will be simply ignored by operator>> when reading into an integral data type.
CTRL-Z / End-Of-File, in contrast, makes any operator>> fail with an error.
See also this SO answer.
Note: Entering f will also terminate your loop, since f is not considered a valid integral number; Hence, std::cin >> value with value being of type int and an input like f will fail as well. To be more accurate: operator>> actually returns a reference to the input stream, but if reading in a value fails, failbit is set on the stream, and then interpreting the stream object in a boolean expression (implicitly calling basic_istream::operator bool()) returns false; So maybe the author of the book did not want to explain these details at the respective section in the book :-)
Is this expected?
Yes, as operator>> ignores leading whitespace by default, which includes line breaks.
If yes, is there any code that stops after inputting a newline?
Use std::cin.getline() or std::getline() instead of operator>>. You can then use operator>> with a std::istringstream to parse values from each line, eg:
#include <iostream>
#include <string>
#include <sstream>
int main()
{
std::string line;
int sum, value;
do
{
std::cout << "Enter a set of numbers, or a blank line to exit: ";
if (!std::getline(std::cin, line) || line.empty())
break;
// read until end-of-line, calculating a running total of all values read
std::istringstream iss(line);
sum = 0;
while (iss >> value)
sum += value; // equivalent to sum = sum + value
std::cout << "Sum is: " << sum << std::endl;
}
while (true);
return 0;
}
Live Demo
Is this expected?
Yes, Thats what while (std::cin >> value) does. See this answer for more explanations: How is "std::cin>>value" evaluated in a while loop?
is there any code that stops after inputting a newline?
No, as >> simply ignore a white space(also #StephanLechner mentioned it)
What you can do instead is:
Just give a condition; if it satisfies just break the loop. you
can also provide a console out to make it more understandable to the
user. For example:
std::cout << "Enter value to sum or press -1 to exit" << std::endl;
while (std::cin >> value && value != -1) // if value == -1, loop stops.
{
sum += value;
}
You can simply terminate by the end of character:
CTRL-Z on Windows
CTRL-D on Mac/Unix

Need help cleaning up fibonacci sequence using C++ please

I'm still very new to C++ still and decided to make a fibonacci sequence. It worked (Woo!) but it doesn't work as well as I would like it to.
what I mean by that is say for example I told my program to count the first 10 terms of the sequence I will get
"0, 1, 1" and then I have to press enter for each additional number until it hits ten in which case the program returns 0 and ends.
How do I get the program to display all the numbers I want to without hitting enter for each additional one?
Here is my script:
#include <iostream>
using namespace std;
int main()
{
int FibNum;
cout << "How many numbers of the Fibonacci Sequence would you like to see? \n\n";
cin>> FibNum;
cin.ignore();
int a = 0;
int b = 1;
int c = 2;
cout << "Fibonacci Sequence up to " << FibNum << " terms.\n\n";
cout << a << "\n" << b << "\n";
for (int c = 2; c < FibNum; c++) {
int d = a + b;
cout << d;
cin.ignore();
a = b;
b = d;
}
}
Thanks in advance for any help!
P.s. Also if you notice anything terrible I'm doing please feel free to correct me, I'm very aware I'm probably doing a lot wrong, I'm just trying to learn. :]
A few things:
1) Remove int c = 2; as you're re-defining c inside the for loop.
2) Drop the line cin.ignore();: in your for loop: that will fix your "enter" problem; that line waits for some input then ignores it.
3) Put some white space in your output: e.g. cout << d << ' ' so your numbers are separated.
4) [Acknowledge vincent_zhang] Consider moving to uint64_t as your data type for a, b, and d. This is a standard type in C++11. It's a 64 bit unsigned integer type; adequate for a large number of terms.
and a small thing, bordering on personal opinion,
5) Use ++c instead of c++ as the former will never run slower as, conceptually at least, post-increment has to take a copy of the original value.
Besides the previous answers,
To better format the output, add white space by changing this
cout << d;
to
cout << d << " ";
You may want to change the type of a, b and d from int to double to prevent overflow.
(If you let FibNum=100 in your code, you should be able to observe overflow, meaning that you are going to get some incorrect numbers toward the end of the sequence.)
Move cin.ignore() out of the loop then you dont need to enter to print all the 10 numbers of Fibonacci series

Confusion about correct design of a program C++

I made a small program that generates primes and lets the user check a number and see if it's a prime or not. Problem is, I'm not sure how to properly design it. This is the program:
#include <iostream>
#include <vector>
typedef unsigned long long bigint;
std::vector<bool> sieve(size_t size)
{
std::vector<bool> primelist(size);
primelist[0] = false;
primelist[1] = false;
for (bigint i = 2; i < size; ++i) { primelist[i] = true; }
for (bigint i = 2; i * i < size; ++i)
{
if (primelist[i])
{
for (bigint j = i; j * i < size; ++j)
primelist[i*j] = false;
}
}
return primelist;
}
int main()
{
bigint range;
bigint number;
std::vector<bool> primes;
std::cout << "Enter range: " << std::endl;
std::cin >> range;
primes = sieve(range);
while (1)
{
std::cout << "Enter number to check: " << std::endl;
std::cin >> number;
if (primes[number])
std::cout << "Prime" << std::endl;
else
std::cout << "Not prime" << std::endl;
}
return 0;
}
The basic flow I want to achieve is: Input range, /handle input/, input number to check, /handle input/
I also want to give the user an option to change the range at any given time, by writing a command like "change range number"
I have a few problems with this:
I want the program to be under control if the user inputs a range bigger than unsigned long long, and if the user basically exceeds any limit(like for example if the range he input was 100 then if he checks for 101) an exception will be caught. I know this needs to be implemented using try/catch/throw, but I have no idea how to do that while keeping the option to change the range and without making my code spaghetti code.
Also, I want the errors to be of enum type(I read that enums are good for exceptions), something like
enum errors
{
OUT_OF_RANGE = 1, //Out of the range specified by the user
INCORRECT_VALUE, //If user input "one" instead of 1
RANGE_SIGNED, //If user inputs a signed value for range
NUM_LIMITS //Number exceeds unsigned long long
};
I have no idea how to use exception handling, not to mention using it with enums. How the hell do I keep this program safe and running, while keeping away from spaghetti code?
I am extremely confused. If someone could help me design this program correctly and maintain readability and efficiency, it will really improve my future program designs.
Thanks for reading!
You asked a lot.
You want to validate user input. Users should not be able to enter huge numbers, non-integers, and so on.
I'm going to start off by answering that this is absolutely not a scenario that exceptions should be used for. Exceptions are used to handle exceptional circumstances. These are ones you can't anticipate or really deal with.
A user enters a number that's too big? You can handle that. Tell them that their number is too big, please enter a number between 1 and X.
A user enters the word apple? You can handle that. Tell them that they can only enter integers.
One way of doing this would be to make a ValidateInput function. You can have it return a number (or an enum, they're basically the same thing) to tell you whether there was an error.
In order to do the validation, you will most likely have to receive input as an std::string and then validate it before turning it into a number. Getting input as an unsigned int or similar integral type doesn't really allow you to check for errors.
This adds a bit of work, since you need to manually validate the input manually. There are libraries with functions to help with this, such as boost::lexical_cast, but that's probably too much for you right now.
Below is some very basic psuedo code to illustrate what I mean. It's only meant to give you an idea of what to do, it won't compile or do the work for you. You could extend it further by making a generic function that returns a message based on an error code and so on.
enum error_code {
SUCCESS, // No error
OUT_OF_RANGE, // Out of the range specified by the user
INCORRECT_VALUE, // If user input "one" instead of 1
RANGE_SIGNED, // If user inputs a signed value for range
NUM_LIMITS // Number exceeds unsigned long long
};
// This function will check if the input is valid.
// If it's not valid, it will return an error code to explain why it's invalid.
error_code ValidateInput(const std::string& input) {
// Check if input is too large for an unsigned long long
if (InputIsTooLarge)
return NUM_LIMITS;
// Check if input is negative
if (InputIsNegative)
return RANGE_SIGNED;
// Check if input is not an integer
if (InputIsNotInteger)
return INCORRECT_VALUE;
// If we make it here, no problems were found, input is okay.
return SUCCESS;
}
unsigned long long GetInput() {
// Get the user's input
std::string input;
std::cin >> input;
// Check if the input is valid
error_code inputError = ValidateInput(input);
// If input is not valid, explain the problem to the user.
if (inputError != SUCCESS) {
if (inputError == NUM_LIMITS) {
std::cout << "That number is too big, please enter a number between "
"1 and X." << std::endl;
}
else if (inputError == RANGE_SIGNED) {
std::cout << "Please enter a positive number." << std::endl;
}
else if (inputError == INCORRECT_VALUE) {
std::cout << "Please enter an integer." << std::endl;
}
else {
std::cout << "Invalid input, please try again." << std::endl;
}
// Ask for input again
return GetInput();
}
// If ValidateInput returned SUCCESS, the input is okay.
// We can turn it into an integer and return it.
else {
return TurnStringIntoBigInt(input);
}
}
int main() {
// Get the input from the user
unsigned long long number = GetInput();
// Do something with the input
}
I like Dauphic's answer, particularly because it illustrates breaking down the problem into bits and solving them individually. I would, however, do GetInput a bit differently:
unsigned long long GetInput() {
// Get the user's input
std::string input;
error_code inputError;
// Repeatedly read input until it is valid
do {
std::cin >> input;
inputError = ValidateInput(input);
if (inputError == NUM_LIMITS) {
std::cout << "That number is too big, please enter a number between "
"1 and X." << std::endl;
}
// ...handle all other cases similarly
} while(inputError != SUCCESS);
// If ValidateInput returned SUCCESS, the input is okay.
// We can turn it into an integer and return it.
return TurnStringIntoBigInt(input);
}
The recursive solution is nice, but has the drawback of, well, being recursive and growing the stack. Probably that's not a big deal in this case, but it is something to watch out for.
As for how to write ValidateInput, basically you're going to be scanning the string for invalid characters and if none are found, testing if the value will fit in your chosen integer type until reading it into a variable with e.g. >>.
note: this solution has a serious flaw in that it doesn't check the state of std::cin. If the user were to pass EOF, i.e. press ^D, the program would get stuck in the loop, which is not good behavior.
Instead of a vector of bool you'd better use a bitset
With that, you can use the Eratosthene method to determine if a number is prime or not.

why it always give zero output?

int i;
cin>>i;
cout<<i
when we entered Character i.e 'A' why it gives Zero output ?
Because A is not a numeric value suitable for storing in an integer, so it will leave your integer alone, as shown here:
#include <iostream>
int main (void) {
int i = 12345;
std::cin >> i;
std::cout << i << std::endl;
return 0;
}
When you run that code and enter A, it outputs 12345 as the value doesn't change.
If you want truly robust input, it's usually better to input lines as strings then convert them yourself.
"Mickey-mouse" programs or those where you have total control over the input can use the sort of input methods you're using, serious code should use more suitable methods.
If your intent is to convert an input character into its integer code, you can use something like:
#include <iostream>
int main (void) {
char c;
std::cin >> c;
std::cout << (int)c << std::endl;
return 0;
}
You should always check if the operation succeeded before continuing.
int i;
if (cin >> i)
cout << i;
else
cout << "Not a valid number!";
because the value 'A' is not stored in the variable i since it is a integer variable. i believe that is the reason the initial value 12345 is printed on the screen...