tags:

views:

47

answers:

2

Say I am looking to receive a series of numeric values and read them into an int, but I also want to test if the user hit key 'x'.

I am sure I am missing something obvious, and have tried a few things but seem to be stuck.

This is what I have so far...
cout << endl << "Enter key (or 'x' to exit): ";
cin >> key;
if (key == 'x') { cout << "exiting";}
// continue on...

+2  A: 

You need to read into a string and then convert that to an integer. In outline:

#include <string>
#include <sstream>
#include <iostream>
using namespace std;

int main() {
  string s;
  cout << endl << "Enter key (or 'x' to exit): ";
  getline( cin, s );
  if ( s == "x" ) {
    // do exit stuff
  }
  else {
     istringstream is( s );
     int n;
     if ( ! is >> n ) {
        // report not an integer
     }
     else {
        // do something with n
     }
  }
}
anon
Thanks for the excellent (and very quick!) reply. I will solve this shortly, but do you know if there is a way that does not play with streams so much?I ask as I am following a beginners book, this is an exercise on chapter 3 where such things have not been introduced; I wish not to appear to cheat myself! :)
Wayne Haworth
@Wayne Streams are the best way of doing this. The alternative is to use the atoi() or strtol() functions to convert the string to an integer.
anon
Thanks a bunch :)
Wayne Haworth
A: 

It depends on how key is declared. If key is an int, you can only test for numbers, of course.

How about the following outline of an algorithm:

int n = 0
bool xentered = false
while (not xentered and there is one more character before EOF)
  if that character is 'x' then xentered = true
  else if it is a digit
     n = 10*n + numeric value of the digit
  else
    error

I leave the task to translate that to the programming language of your choice. :)

Ingo
It is the"if that character is 'x' then xentered = true" that I am stuck on.I have tried doing things like...if (key == int('x') etc to no avail.
Wayne Haworth
Then you should perhaps go back a few chapters in your book, and read again. Or buy a better book.Assuming that we read characters into variable ch, how about ch == 'x'
Ingo
To clarify even more: there are library functions to read characters, strings, integers, etc.The point of this exercise is probably to make you think about which functions you can use to fulfill the specification. Obviously, you cannot use the integer reading functions, as you have also to test for character 'x', and 'x' is not an integer.
Ingo
But you can use character or string reading functions, as the input consists of characters in every case - whether (textual representations of) numbers or Shakespeare poems are typed.
Ingo