Input in array without adding increment operator ++ - c++

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).

Related

What happened when we use cin in for loop condition?

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.

Beginner difficulty with vectors and while-loops in C++

Update:
So it turns out there were two issues:
The first is that I checked the [k-1] index before I checked k == 0. This was a crash, although mostly fixable, and not the primary issue I posted about.
The primary issue is that the code seems to execute only after I press ctrl+z. Not sure why that would be.
Original:
So, learning from Stroustrup's text in C++ programming, I got to an example on vectors and tried implementing it myself. The gist is that the program user enters a bunch of words, and the program alphabetizes them, and then prints them without repeats. I managed to get working code using a for statement, but one of my initial attempts confuses me as to why this one doesn't work.
To be clear, I'm not asking to improve this code. I already have better, working code. I'm wondering here why the code below doesn't work.
The "error" I get is that the code compiles and runs fine, but when I input words, nothing happens and I'm prompted to input more.
I'm certain there's an obvious mistake, but I've been looking everywhere for the last 8 hours (no exaggeration) just devoted to finding the error on my own. But I can't.
int main() {
vector<string> warray; string wentry; int k = 0;
cout << "Enter words and I'll alphabetize and delete repeats:\n\n";
while (cin >> wentry) warray.push_back(wentry);
sort(warray.begin(), warray.end());
while (k < warray.size()) {
if (warray[k - 1] != warray[k] || k == 0) cout << warray[k] << "\n";
++k;
}
}
My reasoning for why this should work is this: I initialize my array of words, my word entry per input, and a variable to index word output.
Then I have a while statement so that every input is stacked at the end of the array.
Then I sort my array.
Then I use my index which starts at 0 to output the 0th item of the array.
Then so long as there are words in the array not yet reached by the index, the index will check that the word is not a repeat of the prior index position, and then print if not.
No matter what whappens, the index is incremented by one, and the check begins again.
Words are printed until the index runs through and checks all the words in the array.
Then we wait for new entries, although this gets kind of screwy with the above code, since the sorting is done before the checking. This is explicitly not my concern, however. I only intend for this to work once.
To end the cycle of input you need to insert EOF character which is ctrl+d. However, there are other problems in your code. You have k = 0 to start with so the moment you will try warray[k - 1] your code will crash.
At the point where you take
warray[k - 1]
for the first time, k is zero, so you want to get the warray value at index -1, which is not necessarily defined in memory (and even if, I wouldn't do this anyway). So as it compiles, I guess the address is defined in your case by accident.
I would try simply reversing the OR combination in your if-condition:
if (k == 0 || warray[k - 1] != warray[k])
thus for the first iteration (k == 0) it won't check the second condition because the first condition is then already fulfilled.
Does it work then?
You're stuck in the while loop because you don't have a way of breaking out of it. That being said, you can use Ctrl + d (or use Ctrl + z if executing on windows in the command prompt) to break out of the loop and continue executing the code.
As for while loop at the bottom which prints out the sorted vector of values, your program is going to crash as user902384 suggested because your program will first check for warray[k - 1].
Ideally, you want to change the last part of your program to:
while (k < warray.size())
{
if (k == 0 || warray[k - 1] != warray[k])
cout << warray[k] << "\n";
++k;
}
This way, the k == 0 check passes and your program will skip checking warray[k - 1] != warray[k] (which would equal warray[-1] != warray[0] when k=0).
You just needed to reverse:
if (warray[k - 1] != warray[k] || k == 0)
to
if (k == 0 || warray[k - 1] != warray[k] )
for terminating this condition if k = 0.
An alternative.
Although it can termed as a bit off topic, considering you want to work with std::vector<>, but std::set<> is an excellent container which satisfies your current two conditions:
Sort the strings in alphabetical order.
Delete all the repetitions.
Include <set> in your .cpp file, and create a set object, insert all the std::string and iterate through the set to get your ordered, duplicate-free strings!
The code:
int main() {
//Define a set container.
set<string> s;
//A temporary string variable.
string temp;
//Inserting strings into the set.
while (cin >> temp) s.insert(temp);
//Create a set<int> iterator.
set<string>::iterator it;
//Scanning the set
for(it = s.begin(); it != s.end(); ++it)
{
//To access the element pointed by the iterator,
//use *it.
cout<<*it<<endl;
}
return 0;
}
I just recommended this container, because you will study set in Stroustrup's text, and it is very easy and convenient instead of laboring over a vector.

I didn't program my while loop correctly

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.

Floating Point Exception C++ Why and what is it?

I'm building a program for the Euler projects question 3, and while that might not really matter as a result I'm current trying to make this code take a number and test if it is prime or not. Now then before I get to troubleshoot the function it gives me the error "floating point exception" right after inputting the number. Here's the code:
int main()
{
int input;
cout << "Enter number: " << endl;
cin>> input;
int i = input/2;
int c;
for (i>0; i--;) {
c= input%i;
if (c==0 || i == 1)
cout << "not prime" << endl;
else
cout << "prime" << endl;
}
return 0;
}
so essentially why is it giving me a floating point exception and what does that even mean?
A "floating point number" is how computers usually represent numbers that are not integers -- basically, a number with a decimal point. In C++ you declare them with float instead of int. A floating point exception is an error that occurs when you try to do something impossible with a floating point number, such as divide by zero.
for (i>0; i--;)
is probably wrong and should be
for (; i>0; i--)
instead. Note where I put the semicolons. The condition goes in the middle, not at the start.
Lots of reasons for a floating point exception. Looking at your code your for loop seems to be a bit "incorrect". Looks like a possible division by zero.
for (i>0; i--;){
c= input%i;
Thats division by zero at some point since you are decrementing i.
Since this page is the number 1 result for the google search "c++ floating point exception", I want to add another thing that can cause such a problem: use of undefined variables.
Problem is in the for loop in the code snippet:
for (i > 0; i--;)
Here, your intention seems to be entering the loop if (i > 0) and
decrement the value of i by one after the completion of for loop.
Does it work like that? lets see.
Look at the for() loop syntax:
**for ( initialization; condition check; increment/decrement ) {
statements;
}**
Initialization gets executed only once in the beginning of the loop.
Pay close attention to ";" in your code snippet and map it with for loop syntax.
Initialization : i > 0 : Gets executed only once. Doesn't have any impact in your code.
Condition check : i -- : post decrement.
Here, i is used for condition check and then it is decremented.
Decremented value will be used in statements within for loop.
This condition check is working as increment/decrement too in your code.
Lets stop here and see floating point exception.
what is it? One easy example is Divide by 0. Same is happening with your code.
When i reaches 1 in condition check, condition check validates to be true.
Because of post decrement i will be 0 when it enters for loop.
Modulo operation at line #9 results in divide by zero operation.
With this background you should be able to fix the problem in for loop.

Exercise Self Study Help

I've started learning C++ and am working through some exercises in the C++ Primer Plus book.
In chapter 5 one of the exercises is:
Write a program that uses an array of
char and a loop to read one word at a
time until the word done is entered.
The program should then report the
number of words entered (not counting
done). A sample run could look like this:
Enter words (to stop, type the word done):
anteater birthday category dumpster
envy finagle geometry done for sure
You entered a total of 7 words.
You should include the cstring header
file and use the strcmp() function to
make the comparison test.
Having a hard time figuring this out. It would be much easier if I could use if statements and logical operators but I'm restricted to using only:
Loops
Relational Expressions
char arrays
Branching statments (ie if, case/switch ) and logical operators are not allowed.
Can anyone give me hints to push me in the right direction?
Edit: Clarification. The input must be one string. So, several words for one input.
Edit: oops, spec says to read into an array of char… I'm not going to bother editing, this is really stupid. std::string contains an array of char too!
cin.exceptions( ios::badbit ); // avoid using if or && to check error state
int n;
string word;
for ( n = 0; cin >> word, strcmp( word.c_str(), "done" ) != 0; ++ n ) ;
I prefer
string word;
int n;
for ( n = 0; cin && ( cin >> word, word != "done" ); ++n ) ;
Use this pseudo-code:
while (input != done)
do things
end-while
HINT: A loop could also act as a conditional...
integer count
char array input
count = 0
read input
while(input notequal "done")
count++
read input
done
print count
The input notequal "done" part can
be done as strcmp(input,"done"). If
the return value is 0 is means
input is same as "done"
reading input can be done using cin
You should define a max len for char arrays first. Then a do while loop would be sufficient. You chould check the string equality with the strcmp function. That should be ok.