my problem is ,,,user will input something like 1+2-3+4-5,,,,, and user will not tell the nth term,,,but i have to calculate the result.how can i calculate this without knowing nth term,,or first term etc. like this problem i have to print (-1) for this series ,and input will be just one line.
Is that a series at all? If it was, the maybe-implied infinite series certainly doesn't converge.
On the other hand, 1 + 2 - 3 + 4 - 5 = -1; this appears to be the the solution.
1 2 3 4
int main() {
using it = std::istream_iterator<int>;
std::cout << std::accumulate(it{std::cin}, it{}, 0) << '\n';
}
the code expects numbers as input and it will output the sum of thos numbers.
the reading will stop when it fails (EOF or a non-numeric input). that part would be equivalent to
1 2 3 4
int n;
while( std::cin>>n ){
//...
}
perhaps the issue is in your input (for example, you put spaces behind the signs)
OK, CL final starts in less than 15 mins (forza Juve!), so my answer is a little bit incomplete - that and this is perhaps
your homework so you need to complete a couple of things yourself, these are mentioned below:
- read the input as a std::string and then 'parse' the string searching for the + or - characters. I've also used a struct
to store the results, so the oustanding tasks for you are:
(a) what if the first char in the input string is not + or - but a number outright - program needs to handle it and
(b) overloading the operator + for struct SignedNum (hint: used std::stringstream)
#include <iostream>
#include <string>
#include <cctype>
#include <sstream>
int main()
{
std::cout << "on a single line enter expression consisting of non-negative integers\n""separatated the binary + or - operators\n""for example: 23 + 52 - 31 + 1 +2+3-4+5\n? " ;
std::string str ;
std::getline( std::cin, str ) ; // read in a complete line
// place the string with white spaces removed into sanitised_str
std::string sanitised_str ;
for( char c : str ) if( !std::isspace(c) ) sanitised_str += c ;
// create an input string stream to read from sanitised_str
std::istringstream stm(sanitised_str) ;
// compute the result and print it out.
int result = 0 ; // initialise to zero
int number ;
while( stm >> number ) result += number ; // note: result + -5 == result - 5
std::cout << "result: " << result << '\n' ;
}