Im trying to write a code in c++ that takes an unknown number of numbers and adds them all together. I do not get any errors but when i input numbers it wont do anything.
#include <iostream>
int main()
{
int sum = 0, val;
while (std::cin >> val)
sum += val;
std::cout << "Sum is: " << sum << std::endl;
return 0;
}
My guess is you never ended your input. It will continue looping and adding numbers until you trigger end of file. Just pressing enter won't do that - you need to hit ctrl+d on Linux or ctrl+z on Windows to end the standard input file, allowing the while loop to exit.
Related
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
Forgive me for my noobishness as I have only just begun learning C++, but I came across something that's confusing me. The following code is me following along the examples from the C++ Primer 5th Edition PDF found here.
#include<iostream>
int main(){
int sum = 0, value = 0;
while (std::cin >> value)
sum += value;
std::cout << "Sum is: " << sum << std::endl; //this doesn't do anything
std::cin.ignore().get();
return 0;
}
Now for some reason, the last std::cout statement doesn't do anything at all, and it's perplexing me as aside from the std::cin.ignore().get() this is the exact same as the example in the pdf and yet this doesn't do anything. What confuses me the most is that if I write value from inside the while loop you can observe that it doesn't recur infinitely; it stops like it should after the last input value, so the error shouldn't be in the execution of the while loop.
Any help is appreciated, thanks!
EDIT: I'm using Visual Studio 2013 Ultimate
EDIT2: The input I'm using is 3 4 5 6
EDIT3: For comparison's sake, here is the code from C++ Primer 5th Edition:
#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;
}
So the ONLY difference between mine and this is the std::cin.ignore().get().
while (std::cin >> value) means it will not stop until failed to read an integer, i.e encountering an EOF or a non-integer input.
On Windows, use ^Z (CtrlZ) to enter an EOF.
Try input:
1 2 3 4
^Z
It should hit the cout line. And it's totally a different question about the cin.ignore() stuff.
I'm in an introductory C++ class at my university. We were assigned a project to create a program to approximate pi using a series where pi=summation ((-1)^i+1)*(4/2i-1).
I need my output to look like this:
This program approximates pi using an n-term series expansion.
Enter the value of n> 6
pi[6] = 4[1-1/3+1/5-1/7+1/9-1/11] = 2.9760461760417560644
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
int main()
{
int numOfTerms;
cout <<"This program calculates pi using an n-term series expansion."<<endl;
cout <<"Enter the value for n>";
cin >>numOfTerms;
if (numOfTerms<=0)
cout <<numOfTerms<<"is an invalid number of terms."<<endl;
else
{
cout <<"pi["<<numOfTerms<<"] = ";
int i;
for (i=1; i<=numOfTerms; i++)
{
double pi, sum, firstTerm, secondTerm;
firstTerm=pow(-1,(i+1));
secondTerm=1/(2*i-1);
pi=firstTerm*secondTerm;
{
if (pi <= 4)
cout <<firstTerm<<"/"<<secondTerm;
else
cout <<"You have a C++ math error.";
}
sum=sum+(4*pi);
cout <<" = "<<sum<<endl;
}
}
return 0;
}
I have an earlier version of the code that correctly sums the n-series approximation but it does not display expanded series that equals the sum.
My current version does not display the correction summation, but it display pi[n] on the screen n times over n lines.
I'm willing to try to figure the majority of the project on my own, I just need to know if there is a way to get the output of my loop to display on one line instead of each iteration displaying on its own line.
Dont use endl and your job will be done.
endl
Inserts a new-line character and flushes the stream.
Its behavior is equivalent to calling os.put('\n') (or
os.put(os.widen('\n')) for other character types), and then
os.flush().
Three things:
First, change your calculation of secondTerm for the following:
secondTerm=1.0/(2*i-1);
This way, you are forcing it to be a double (otherwise, it would return an int, which we do not want).
Second, change this line:
cout <<firstTerm<<"/"<<secondTerm;
for this line:
cout <<pi;
That is because secondTerm holds the result of the division, not the denominator.
Third, move this line:
cout <<" = "<<sum<<endl;
after the for loop, because that prints the final result, which you would do after you sum all the terms. Having that line inside the for is causing the line breaks. If you do this, you will need to move this line:
double pi, sum, firstTerm, secondTerm;
before the for loop, so the sum variable continues to exist afterwards.
If you do all this, the program will work fine (although it prints all the terms without any spaces between them).
Don't use endl. This causes a line-break.
Im writing an application for my intro to programming class and the objective is to
set up a simple program that prompts the user to enter a series of positive integer numbers between 50 and 100 (inclusive) using the keyboard. Your prompt should tell the user to enter a negative number to stop the input process.
As the user enters the numbers, you should keep track of the number of valid entries they have made (those that fall in the allowed range), and add up those numbers entries. You do not need to store more than the single entered number, the count, and the current total you are calculating.
Once the user completes the data entry, produce output similar to this:
A total of 5 values were entered.
The sum of those numbers is 127
make a program that will have one variable and it will retrieve the users
Here is the code I wrote
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char *argv[]) {
int loop = 1;
int value;
int times = 0;
cout << "Enter a negavtive number to quit" << endl;
cout << "\nPlease Enter Any Number Between 50 - 100" << endl;
while (loop == 1) {
cin >> value;
times++;
value += value;
if(value < 0) {
cout << "You entered " << times - 1 << " numbers" << endl;
cout << "Total: " << value << endl;
system("PUASE");
return EXIT_SUCCESS;
}// end if statement
} //end while loop
system("PAUSE");
return EXIT_SUCCESS;
}
Here is the output
http://www.flickr.com/photos/62751645#N08/6286454476/
I think it may have something to do with the fact that I am using the int value to do two different tasks.
How might I go about fixing this?
revision
thanks to all of you for the "fix"
I add a new variable and it works like a charm, but now the math is not adding correctly
http://www.flickr.com/photos/62751645#N08/6286526294/in/photostream
There are a few problems, but the major one is this:
cin >> value;
This means "overwrite value with the number the user inputs", and of course if you do that you will never be able to store a sum inside value because it will be overwritten each time with the new number.
Solution: use another variable to keep the running total.
You also have a bug in that you do
times++;
value += value; // which as described above will not "stick"
before checking if value is negative. These operations should only be performed when value is not negative; otherwise, data entry should stop immediately and the negative number should not be taken into account for summing the total.
add a sum variable to hold the sum, you overwrite the input value in every loop iteration.
sum += value;
Don't use value to do two different tasks.
Have another variable called sum and accumulate the total there.
The way you're doing things you are writing over your sum every time the user enters a number:
cin >> value; // sum of previous values is overwritten!
Also there's another problem in that when the user enters a negative number you add that to the sum as well.
Your code does not check whether the values are in range (i.e. between 50 and 100). You can put a condition on the line where you do the addition as below:
if (value >= 50 && value <= 100)
sun += value;
Also, you can use 'value' to break the loop also.
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.