The code below works fine on HackerRank, but not on Xcode 11. I suspect the while loops are causing the issue. Is there something I am missing?
This is not the first time code works on HackerRank, but not Xcode. I usually work on Xcode before submitting it to learn. I would like to make sure the code I write on Xcode will work on any compiler.
I would appreciate some insight.
int main(){
int n, i=0;
cin >> n;
int * A = new int[n];
while(cin >> A[i++]);
while(cout << A[--n] << ':' && n);
delete[]A;
return 0;
}
The question is:
User will need to enter the size of an array and the elements of the array on the same line separate by a space. The program will return the array in reverse order.
sample input: 4 (enter)
sample input: 1 2 3 4 (enter)
sample output: 4 3 2 1
When I try running on Xcode it seems to loop forever after I manually input the values. The cursor just blinks. I have to force quit. I do not get any errors. See image in the link below.
Xcode debug area image
while(cin >> A[i++]);
Will wait forever for the next input value until it encounters the end of the input or an invalid input value.
This will be working on hackerrank because they will be piping in a file with the input values so cin will report eof when you try to read too many values.
As you know exactly how many inputs you expect the easiest (and safest to prevent out of bounds array access) solution is to add s check for how many inputs you have read:
while(i < n && cin >> A[i++]);
Related
This question already has an answer here:
How to reset std::cin when using it?
(1 answer)
Closed 2 years ago.
I am writing a simple piece of code for a bigger project, now this piece of code asks a user to enter two arrays - X and y.
vector<double> X;
double element;
while (cin >> element)
{
X.push_back(element);
}
cout << "Enter array y: " << endl;
vector<double> y;
while (cin >> element)
{
y.push_back(element);
}
The user successfully enters the first array, but right after being promted to enter the second array, the program exits.
I believe it has something to do with the fact, that the first array is read until the user enters an element that is outside the 'double' format. For instance, the array X is pushed into the X variable until the user enters ';'. After that the second time the while loop starts, cin already sees the ';' and that is why the second array never gets to be entered. Is it correct? How do I go about it?
These lines are something like within my first 500 lines of c++ code in my life, so don't go easy on me!
Thanks a lot in advance!
The first loop will go on for as long as extracting a double succeeds. When it eventually fails, the stream (std::cin) is set in a failed state and any further extraction will also fail, so your second loop will fail immediately.
One possible way to fix that is do reset the state and ignore the rest of the line after your loops:
// reset the failed state
std::cin.clear();
// ignore the rest of the line
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
What is causing my code to behave unexpectedly?
The program is freezing (not crashing) before it reaches expected part of the code. The program is fully contained inside main(), and isolating the whole code the expected statement makes it work correctly. Why is it happening?
I was coding a yet poor solution for this codeforces problem, that I was intending to refine little by little. The problem is that curiously my program freezes when reading the input (like if it was an infinite loop, it doesn't crash). I tried both C++ and C++11 on GCC, and both of them froze. Tried Ideone, and the same happened. It could be anything, except that I copied everything from the first include to the output line that would confirm that all the input was read and ran only this excerpt.
#include <bits/stdc++.h>
using namespace std;
typedef unsigned uint;
int main() {
ios_base::sync_with_stdio(false);
uint n, h, k, buf;
vector<uint> potatoes;
cin >> n >> h >> k;
for (uint i = 0; i < n; ++i)
{
cin >> buf;
potatoes.push_back(buf);
}
cout << "Letf\n";
return 0;
}
This is a reduced version that contains all the lines that are part of the logic of the input stage. The expected input is
5 6 3
5 4 3 2 1
Here are the links for the full code and the correctly working excerpt.
The main problem is your while (true) {...}. Your "algorithm" makes this loop infinitely.
And if you don't know, there is an Tutorial and source code for the round already
http://codeforces.com/blog/entry/45181
Finally, please look carefully at the problem page. The Contest Materials part have useful things for you.
So I want to accept two inputs, a string and an int, and when the user enters "end" to exit out of the loop.
My problem is when "end" is entered that it gets stuck in a loop, since (I'm assuming) it is expecting two inputs when the user only types in one.
I've done some research and found stuff on discarding the input and resetting it with cin.ignore() and cin.clear(), however, these seem to only apply when accepting a single input, where as I'm asking for two separate inputs on one line, and it doesn't seem to work.
What my code is doing is basically asking for a list of things (name value), storing it in an array in a class, and is capped at 10 items. So, when "end" in entered, it only needs to exit the while loop. Everything else seems to work fine, i.e. when I enter 10 items it exits the loop and the rest of the code executes like it should. So there just seems to be a problem when typing in 'end'. (p.s. a is a string and b in an int type).
The section of code is:
do {
cout << "Enter the item and value (enter 'end' to stop): ";
cin >> a >> b;
items1.set_name(a, i);
items1.set_price(b, i);
i++;
} while ( i < 10 && a != "end" );
This seems like it should be very simple, and I'm sorry if its a stupid question, but I can't figure it out hahah.
Thanks in advance for helping me out.
You need to test the value of a BEFORE proceeding to read b; something like this:
cin >> a;
if(a == "end")
break;
cin >> b;
To get out of the loop, use
if (a == "end" || b == "end") break;
here is the code that I have
int main()
{
int total = 0;
int count = 0;
std::cin >> total;
int arr[4] = {0,0,0,0};
while(count < total)
{
std::cin>>arr[0]>>arr[1]>>arr[2]>>arr[3];
count++;
std::cout<<count<<std::endl;
}
return 0;
}
so the first line of input tells how many lines I need to read after..and each line has 4 numbers separated by space. Whenever the number of lines exceed 80(e.g 100), then the while loop gets stuck. I have no idea what causes the problem and I have tried a couple things like cin.clear() but they just didnt work....
Edit: std::cin stops reading after 80 lines of input with format like 10 20 210 10
Xcode with LLVM didn't work...However g++ using terminal works.... http://melpon.org/wandbox/permlink/UXAMgM4ldn2K2NgU
here is the code that works on my terminal with g++ but not my xcode...
It's the output that's getting stuck. Unless the output of the count is being read by something and consumed, eventually the output buffer will get full and the cout line will block.
I rewrote this loop in several ways, with nested Ifs and do whiles, yet behavior is the same. It behaves as expected as long as the user does not enter a character or a string. Once the user does it just goes on spinning the loop until I CTRL+C it.
From what I have researched, when a variable is a number and the user inputs a char or a string, they just get converted into their ASCII numbers, in which case the while check should work. The number should be larger than allowed and the user should be prompted for a new value right? Why does it keep looping infinitely?
Width is declared as a float.
void setWidth ()
{
std::cout << "\nPlease enter the width (use numbers greater than 0 and no greater than 20.0).\n";
std::cin >> width;
while (width <= 0 || width > 20)
{
std::cin.clear();
std::cin.ignore();
std::cout << "You have entered a number outside of the allowed range.\nPlease enter a number greater than 0 and no greater than 20.\n";
std::cin >> width;
}
}
Like I said, for numbers it works great, doubles, negatives, whatever. But something like "asdf" or "a" will put it in infinitely spinning loop.
It seems like I've tried everything. Why does this happen? I mean I know why it loops, it's because the number is not between 0 and 20, but why does it not ask user for input? I do clear the buffer.
The line std::cin >> width; fails because the input isn't a number. It also doesn't consume any of the input, so you are stuck in an infinite loop.
To avoid this, you should read the input using std::getline(), then try to convert it (std::ostringstream is one option), handling and reporting failures accordingly.
The default for cin.ignore() is to ignore just a single character.
If you want to ignore longer strings, you have to add extra parameters for that, perhaps cin.ignore(1000, '\n') which skips up to 1000 characters or the next newline (whichever comes first).
cin::clear() "Sets a new value for the error control state" 1, but the remaining input is still here and still read.
Then I guess the actual behavior depends on the compiler since when I compile it with g++ 4.6.3 and type the input "abc", it only loops three times and then wait for another input.
To empty the cin buffer you may rather see How do I flush the cin buffer?
Try checking the failbit on cin
Ok, thanks for all the help guys... I finally managed to get it to work with cin (not getline), by doing exactly what ive been doing, except I made a clearBuffer() function. So instead of clearing the buffer from within the getWidth function, the getWidth function calls another function.. thereby leaves the getWidth function to execute some code... then comes back to run the rest of it...
For some reason when it goes outside of the function it works fine and strings and chars trigger the error.. but if the cin.clear and cin.ignore are kept within the function then I have that problem.
So the final code looks like this.
void clearBuffer()
{
std::cin.clear();
std::cin.ignore(80, '\n'); //Ignore the first 80 characters up to an Enter character.
}
void setWidth ()
{
std::cout << "\n\t\tPlease enter the width.\n(use numbers greater than 0 and no greater than 20.0).\n";
float temp = NULL; //Using temp here so that we dont write invalid characters to an actual variable.
std::cin >> temp;
clearBuffer();
while (temp <= 0 || temp > 20)
{
std::cout << "\nERROR: You have entered width outside of the allowed range.\nPlease enter a number greater than 0 and no greater than 20.\n";
std::cin >> temp;
clearBuffer();
}
if(temp > 0 && temp <= 20)
width=temp;
}