Code excerpt freezes unexpectedly only when with full code - c++

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.

Related

Scan characters depending on a pattern

I found this code in a competitive programming book for ICPC. The objective is to scan inputs which have a pattern where there are N numbers like 0.4586... (starting with 0. and terminating with ...). I tried giving the inputs but on pressing enter key the entire while loop executes at once and I don't get the chance to input the numbers. So I tried using spaces but that doesn't work either. Nothing gets scanned in the while loop however the code works fine if I remove the while loop.
Can someone explain this behaviour.
#include <bits/stdc++.h>
using namespace std;
char digits[100];
int main() {
int N;
scanf("%d", &N);
while (N--) {
scanf("0.%[0-9]...", &digits);
printf("the digits are 0.%s\n", digits);
}
}

Why does some code work HackerRank but not Xcode

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++]);

C++ Xcode won't run my for loop (very short) [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I want to continue reading Stroustrup PPUC++, but I'm stuck! I wrote a BleepOutTheBadWords program a few days ago and it worked. I tried to write the program with my younger brother a few days ago and I failed. This is essentially a program I wrote to figure out what is going wrong. It is not printing out each word in the "sentence" vector.
#include <iostream>
#include "std_lib_facilities.h" // Stroustrup header file
using namespace std;
int main()
{
cout << "Write a sentence." << endl;
vector<string> sentence;
// Put user input into "sentence" vector
for (string word; cin >> word; )
sentence.push_back(word);
// Print each word in "sentence" vector
for (int i = 0; i < sentence.size(); ++i)
cout << sentence[i] << endl;
// Keep window open and return 0 to show program succeeded
keep_window_open();
return 0;
}
The answer is going to be obvious. Please just state the obvious if you are so kind. I looked through the suggested readings on two different pages before posting this.
XCode won't run my for loop
Your loop is running. The thing that you missed is how to terminate the loop.
for (string word; cin >> word; )
This loop will terminate when cin >> word evaluates to false. Normally, i.e. without an error condition, it will evaluate to false when your input is finished. The exact process to signal an end of stream, or EOF, is platform dependent. If you are running this program on OSX then the most common way to signal EOF is to hit Ctrl + D button, unless you changed the default configuration of your keyboard. Once you signal EOF this input loop will terminate and you will be able to see the output.
I'm pretty much sure that Stroustrup discussed this on his book (though I can not refer to an exact page number). However "Chapter 10: Input and Output Streams" of his books covers these things in detail.

Why does my code terminate without explanation?

I'm learning c++ again after having not touched it for the last few years, and I've run into a rather peculiar bug that I can't seem to figure out.
When I run the code below, it will accept 10 inputs as I expect it to, but immediately after the first for loop, the program exits. I have run it ingdbto try and figure out the issue, but it reported that the process 'exited normally'.
I compiled using g++ -std=c++11
#include <iostream>
#include <string>
using namespace std;
int main() {
//User inputs
string input[10];
//Get the inputs
for(int i = 0; i < 10; i++) {
//Get this input
printf("%i> ", i);
getline(cin, input[i]);
}
//The application does not make it to this point
//Collected
printf("Thank you for submitting your data.\n");
//Print inputs
for(int a = 0; a < 10; a++) {
//Show the input
printf("%i> %s\n", a, input[a].c_str());
}
}
Based on what you're describing, it sounds like stdout is not being flushed before the program ends. That's unusual; normally, stdout is automatically set up for line-buffered operation in which case it will be flushed as soon as a newline is encountered.
Your best bet is to follow #NathanOliver's advice and use cout << ... rather than printf. The printf command is a throwback to C, and you're using a C++ compiler and C++ features. In fact, you're not even including the header that's usually required for printf, so I'm a little surprised it even compiles.
FWIW, if you choose to continue using printf maybe try manually flushing stdout at the end like so:
fflush(stdout);
Your application does what is supposed to do:
Application will pause at getline() (10 times) (because getline is blocking execution), then it will do some for loops, print something and end (probably closing console window). If you add something at the end to block execution (such as cin.get(), which waits for enter key press) you will see results (because application won't terminate). If you run your code somewhere where output is not removed after program has ended you will see what was printed.

Query regarding SPOJ TEST

I might be wrong in asking an SPOJ problem on this forum but I wanted to understand one mechanism which I wanted to know from the enriched community here.
Your program is to use the brute-force approach in order to find the Answer to Life, the Universe, and Everything. More precisely... rewrite small numbers from input to output. Stop processing input after reading in the number 42. All numbers at input are integers of one or two digits.
Example
Input:
1
2
88
42
99
Output:
1
2
88
My Solution:
#include <iostream>
using namespace std;
int main()
{
int n,i=0;
int a[100] = {0};
while((cin>>n))
{
a[i] = n;
i++;
continue;
}
for(int j = 0;a[j]!=42;j++)
cout<<a[j]<<endl;
return 0;
}
Good Solution:
#include <iostream>
using namespace std;
int main()
{
int n;
while(true)
{
cin>>n;
if(n == 42)
break;
cout<<n<<endl;
}
return 0;
}
My query is what happens to the input in the good solution?We would be running the loop only till the number is not 42.How does Good solution handle the remaining input?I got some hint that it is somewhat related to buffering and all.Please provide me some explanation or links or study material or at least some keyword to google etc to get clarity on this.
Remaining input in good solution will be ignored by "good solution".
If you need more info read:
object
std::cin
extern istream cin;
Standard input stream
Object of class istream that represents the standard input stream oriented to narrow characters (of type char). It corresponds to the C stream stdin.
The standard input stream is a source of characters determined by the environment. It is generally assumed to be input from an external source, such as the keyboard or a file.
object
stdin
FILE * stdin;
Standard input stream
The standard input stream is the default source of data for applications. In most systems, it is usually directed by default to the keyboard.
stdin can be used as an argument for any function that expects an input stream (FILE*) as one of its parameters, like fgets or fscanf.