Click here to Skip to main content
15,892,199 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C++
// Write a program to calculate the addition of  integers and print the output.As we  //are taking integer as input from user we don't know exact number of inputs  he/she is //going to press.

// Input Format:
// line 1: Integers delimited by space

// sample input: 3 4 5 6 7
// sapmle output: 25

// sample input: 3 5 a b 7
//sapmle output: Invalid Input

// Now check what i have tried you will get real problem what i meant to say

#include<iostream>
#include<string>
#include<cstdlib>
using namespace std;
int main()
{
  string temp;
  bool enter = false;
  bool bad_ip = false;
  int sum = 0;
  int a = 0;
  
  
  while(!enter)
  {
      getline(cin,temp); 
      
      if((cin >> a).fail())
      {
         bad_ip = true;
         cout << "Invalid Input" << endl;
         cin.clear();
         exit(1);
      }
      sum += a;
      if(temp.empty())  // i can't compare with newline or enterkey
      {
        cout << sum;
        enter = true;
        break;
      }
      
  }
 
 return 0;
}


What I have tried:

I tried if(a == '\n') condition track for enter key
Posted
Updated 8-Jun-16 21:35pm
v2
Comments
Sergey Alexandrovich Kryukov 8-Jun-16 20:59pm    
It is console input, or what? If this is console input, it's better to read line by line; in this case, you get rid of recognition of new line. Note that end of line characters are platform-dependent.
If you need to detect keys in UI, first thing to understand is: keys are not characters at all.
—SA
Rahul Thengadi 8-Jun-16 23:10pm    
It is console input and input should separated by space.
Im using fedora
Sergey Alexandrovich Kryukov 9-Jun-16 0:09am    
Fedora, Juliana... Linux is Linux. Indeed, it's LF, '\n'. I already advised, you can avoid detecting it if you read line by line.
What have you tried so far?
—SA
Rahul Thengadi 9-Jun-16 0:18am    
But in the problem it is clearly specified that the the integers are delimited by space and should be accepted through console.
I tried getline(cin,temp) and then check the temp.empty().But as i used getline method i can't check whether user has given correct input
Sergey Alexandrovich Kryukov 9-Jun-16 1:28am    
Yes, of course, but this is a trivial problem unrelated to Enter key. Parse the string using spaces as delimiter. What's the problem? (See my link above.)
—SA

1 solution

You could use a istringstream object, try:
C++
 #include <iostream>
 #include <sstream>
 using namespace std;

int main()
{
  string s;
  int a;
  for (;;)
  {
    getline(cin,s);
    if ( s.empty()) break;
    istringstream iss(s);
    iss >> a;
    cout << a << endl;
  }
}
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900