如何在扫描输入时检查输入键 [英] How to check for enter key while scanning input

查看:81
本文介绍了如何在扫描输入时检查输入键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

// 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;
}





我的尝试:



我试过(a =='\ n')条件跟踪输入键



What I have tried:

I tried if(a == '\n') condition track for enter key

推荐答案

你可以使用 istringstream 对象,请尝试:

You could use a istringstream object, try:
 #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;
  }
}


这篇关于如何在扫描输入时检查输入键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆