This is a model solution code of the following problem;
"The input consists of T test cases. The first line of the input is given a T.
Each test case consists of three rows of integers separated by a single space, each consisting of three random points of x and y coordinates. The coordinates of the top left pixel in the browser viewport are (1, 1) and the coordinates of the bottom right pixel are (1000, 1000). All coordinates are located within the viewport and the positions of each point are different."
And here is the sample of the input.
2
5 5
5 7
7 5
30 20
10 10
10 20
7 7
30 10
The last two lines are the answers of the problem.
And here is my three questions.
1) What happened when we use cin statement in initialization?? It receives how many actions it will perform from the user in the initialization of for loop. I understand that this cin statement works properly. I cannot understand how this code knows how many times this for loop has to be repeated. This is because there is no action on T after initialization with a value of T from the user. There is no actrion in 'increment/decrement' also.
2) After googling, I understand when there is cin in condition, the loop ends when there is no more inputs or the inputs' type does not match the variables' type. But in this code, the for loop ends when the repeated time (T) is over. How could this happen???
3) Finally, the outcomes should be presented after all inputs are finished not by one-by-one. Then how could this for loop memorize the outcome of each set(3 inputs)??
I'm not English speaker T.T Thank you for reading my question.
#include<iostream>
int main()
{
int T,a,b,c,A,B,C;
for(std::cin>>T; std::cin>>a>>A>>b>>B>>c>>C; printf("%d %d\n",a^b^c,A^B^C));
}
What happened when we use cin statement in initialization??
That part of for() loop can contain any simple statement, not
just initialization statement. This statement is done only once. For
loop
for ( init condition ; iteration )
statement
is actually equivalent of this code:
{
init
while ( condition )
{
statement
iteration;
}
}
But in this code, the for loop ends when the repeated time (T) is
over. How could this happen???
The operator >> overloaded for streams return stream it acted on. Class
ios_base which is common parent of all streams, contains this
operator
std::ios_base::operator bool()
This operator is an equivalent of good() method. When >> fails to read and parse values from input stream, good() returns false,
loop breaks. T is not used in the provided code.
Then how could this for loop memorize the outcome of each set(3
inputs)??
It doesn't. It prints result after reading each set.
PS. People who read\proof-check code after programmer, would tend to have murderous intent toward those who write for() loops like that.
If we use a cin statement as our initialization, we execute this once. It will receive the input and place the value in the variable T. You are completely right; there is no action on T after initialization such as incrementing or decrementing its value.
This is not true. The code does not end when the it repeated T times. As long as (valid) input is given, this for-loop will continue. This is because the condition part of your for-loop consist of a cin statement. That is, as long as your cin statement succeeds, the for-loop will continue.
It cannot. Each time the loop runs, you overwrite the variables a, A, b, B, c and C. Hence, the old values are lost.
Related
Note: I know the solution that would solve the issue, but I don't understand the "computer logic," or what is going on behind the compiler.
In my C++ textbook, there is a blurb of example code that reads:
cout << "Enter a line of input:\n";
char next;
while ((!isdigit (next)) && (next != '\n'))
{
cin.get (next);
cout << next;
}
cout << "<END OF OUTPUT>";
... Paired with the example input: I'll see you at 10:30 AM.
I would expect, after typing in the input, for the output to be I'll see you at <END OF OUTPUT>. Instead, the first digit, "1," is also output, such that it becomes I'll see you at 1<END OF OUTPUT>. Why is this? Is this because the statement cin.get (next); is not declared/initialized outside of the while loop, and thus the first next value tested in the while loop's conditional parameters is not actually the first character of the keyboard input? Or does the while loop run an extra iteration when the next condition is not satisfied?
If it's the former, what does the computer test if next is not set to a value? And why does the first digit ("1") read still meet the condition to run the loop again one more time before terminating?
As mentioned in the comments, you have to initialize next before using it, otherwise it is undefined behavior.
Now lets assume, next is properly initialized to a non-digit character. The condition (!isdigit (next)) && (next != '\n') is checked once when you enter the while loop and every time when you reach the end of the statement in curly braces. In your first version, you get a new char and immediately stream it to cout. The check is done afterwards and the loop terminates as expected.
I am currently learning C++ at my school, and am making a word sleuth as part of a project that I have to submit. For this, I have already made the grid of alphabets and other necessary things (clues, rules, etc.). I am taking the input in the form of coordinates in an integer array whereby the user enters 4 values in the array, signifying the initial row and column number and the final row and column number, corresponding to which are the first and last alphabets of a particular word.
After doing this, I am now comparing the array input by the user with the array I have already defined that has the coordinates of that particular word. This is shown here :
cout<<"Enter the coordinates of starting and final characters : row1 col1 row2 col2 "<<endl;
for (z = 0; z < 4; z++) //first for loop
cin>>p[z]; //taking the input as an array 'p'
for (b = 0; b < 4; b++) //second for loop
{
if (p[b] == messi[b])
b+=0;
}
if (b == 4)
cout<<"Great!!!! You have answered the question correctly"<<"\n\n";
else
cout<<"You got this one wrong mate! Try again :)"<<"\n\n";
Here, messi[b] is the array which has the coordinates corresponding to the word 'MESSI' in the grid. Now, to my mind, the 'if' statement after the second for loop must contain the condition to check if b = 3. However, when I do that, the output always comes out to be what the 'else' statement says i.e. "You got this..." for every input. However, when I impose the condition to check if b = 4, the output comes out to be what the 'if' statement says i.e. "Great!!..." for every input.
What wrong am I doing? I hope I am clear enough in explaining the problem to you. I am using CodeBlocks 16.01.
It's a bit unclear what you are doing, as the program stands, b will always be equal to 4 after the second for-loop since the last time to condition was true, b < 4. So after the increment, it will be 4.
Inside the second for-loop you also have the NOP code b += 0; which does absolutely nothing to the code. What is the intention here?
I would like some confirmation (or refutation) about something.
I was just busy with a simple exercise placing statements inside loop conditionals. Basically I created an array of 5 elements and then have the user input 5 values that will be stored in the array. Pretty basic stuff. But then I started wondering: What if I replaced the a[i++] in my code with simply a[i]? So I did, and the resultant output was that I (i.e. the user) just kept inputting values seemingly infinitely, i.e. not stopping at only 5 inputs.
Now then I made the assumption that what might be happening is that now the program simply replaces every new input value with the previous one and storing it in element 0 of the array, over and over, hence it not stopping at 5.
Is this assumption of mine is correct? If not, then please shed some light on what exactly is happening here. This might be a very nonsensical thing to be concerned about, but I'd really like to know either way.
//array test
#include <iostream>
int main()
{
int a[5] = { 0 };
int i = 0;
while(std::cin >> a[i++] && i < 5);
return 0;
}
So, you are basicly asking what's the difference between i and i++? It's rather basic C/C++ (note the ++ here!). I suggest you google for "C++ postincrement operator" :)
If you remove the i++ and replace it with only i, you are replacing a[0] indefinitely.
a[i++] evaluaves to a[i], and AFTER that increases i by one. So when i reaches 5, the second part of your condition (i<5) is not true and exits from the while loop.
Yes, you're correct.
Just test it, remove the ++ and run.
If you want "having a loop with no code inside", do not use std::cin >> a[i++] expression as condition (I think it will always true). Better use comma operation, e.g.:
while(std::cin >> a[i++], i < 5);
Moreover, in the condition expression like (std::cin >> a[i++]) && (i < 5) left part (i.e. (std::cin >> a[i++])) can be skipped because optimization done by compiler (so i++ will not be executed).
I wish to take inputs from console where the number of inputs are not known. All i know is that they are less then or equal to 10.
I wrote this code but it evaluates the last value twice.
int x;
do{
cin>>x;
cout<<check(x)<<"\n";
}while(std::cin);
The inputs are in this form:
12
2
45
As #LightnessRacesinOrbit commented, it's while(!eof) bug again. You should check the stream state after reading from it, not before.
You can use cin>>x in the while-condition and apply a special value (i.e. anything not a number) as the end flag like this:
while (cin >> x)
{
// got a value
}
You may use istream::geline.
char input[1024]
std::cin.getline (input,1024);
After you read the line, you have to split it by white-spaces as delimiter. Just ignore 11th split onwards. And you may apply atoi or similar functions on the splits (some_split.c_str()) to get the numeric values
printf("What do you do?\n1. Walk Away.\n2. Jump.\n3. Open Door.\n\n");
scanf("%d",&Choice);
printf("\n\n\n");
while(4<=Choice,Choice<=0);
{
printf("That is not a choice.\n");
printf("What do you do?\n1. Walk Away.\n2. Jump.\n3. Open Door.\n\n");
scanf("%d",&Choice);
printf("\n\n\n");
}
So this is my program. It works but what I want it to do is to repeat until an answer of 1, 2, or 3 is put in. But no matter what the answer is it has it go through the while loop then continue regardless of the next choice. (Also, I did declare "Choice"; I just didn't want to show the whole program.)
There are two problems in your code. Your while-loop expression is incorrect. The comma does not do what you think it does: in C/C++, the comma executes the left-hand expression and evaluates to the right-hand expression, meaning that in your case you are only checking the second condition. You probably want:
while(4<=Choice || Choice<=0)
The || is the OR operator, which returns true if either of the expressions around it are true.
Secondarily, there is a misplaced semicolon at the end of the while loop:
while(4<=Choice,Choice<=0); //<-- this should not be here
This marks the end of the loop, meaning that your code is parsed as:
while(4<=Choice,Choice<=0); //loop body is empty
{
//and we have a random unnamed block following it
}
Remove the semicolon and your while loop should execute correctly.
C and C++ have a comma operator, which has the lowest precedence of all operators. It evaluates the left operand and throws the result away, and then evaluates the right operand. Thus, your while condition is equivalent to:
while (Choice <= 0)
You also have a bug because there is a semicolon immediately after the condition, which makes for an infinite loop if Choice is not strictly positive (because nothing in the loop changes the value of Choice).
What you probably intended to write was:
while (Choice >= 4 || Choice <= 0)
{
...
}
The comma operator , doesn't test both conditions, it simply returns the second of the two. So your while loop is the equivalent of:
while(Choice<=0) ;
and since there's a ; following the statement, it is in fact an infinite loop if the condition is met. Good thing you didn't enter a choice of -1.