Cin to two different variables

Pages: 12
Hi, I'd like to make a single input through a cin, and depending on if the input is a char or an int have the corresponding code happen.

Thanks in advance! :)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
 #include <iostream>
using namespace std;

int main(){
	int n = 0;
	char a = 0;
	cout << "Input a number to learn the ASCII character of that number, or a character to learn the number of that character: ";
	
	//want one input to result in the corresponding statement based on the fact that it's an int or a char
	cin >> n;
	if (cin){
		cout << "The character is: " << (char)n << endl;
	}
	else {
		n = a;
		cout <<"The number is: " << (int)a << endl;
	}
	return 0;
}
Accept input as a string and then examine the string. Do not ignore the possibility of the input being neither a character nor an integer. Don't forget the user can end the input stream at any time and your program's attempts to read input will fail.
Furthermore, only small numbers are ASCII codes and some of valid codes are not printable characters.


You did not ask a question, but I'll still note that
1. if line 11 fails, then line 10 has already failed and the content of 'n' is standard-dependent.
2. C++ has an elaborate cast syntax; you use the less controllable C syntax.
@UnseenDragon:

You can read the character in as a char first, then convert to ASCII number by type-casting as int.

1
2
3
char inputChar = 0;

cout << (int) inputChar;


@squished18 that is not useful in this context, unfortunately.
@Squished

That will not work, as I'm intending to be able to input a number to get the symbol, as well as the other way around, otherwise that would be the correct solution, yes. :)

@LB

How would I examine the content? (any links would be helpful)
I was thinking about it, but then converting it seemed like too much of a hassle :/

@keskiverto

Yeah, I know the first 13 or so will not print anything, however that's not an issue as this is mostly for me copy-pasting characters or inputting numbers for other programs

EDIT: about the line 10/11, that's why I'd like to input the cin into both the char and the int, if the int fails go to the char, if the char fails return error :)
Last edited on
Reading a string from a stream always succeeds (unless you've reached the end of the stream), so you can take advantage of that and let temporary stringstream objects be placed into error states instead of your global input stream.

Demo:
http://ideone.com/Jk5Pos
Note that there are two newlines at the end of the input.
Last edited on
How about this?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
 #include <iostream>
 #include <cstdlib>
 
using namespace std;

int main(){
	string string_to_convert = "";
	
	cout << "Input a number to learn the ASCII character of that number, or a character to learn the number of that character: ";
	
	//want one input to result in the corresponding statement based on the fact that it's an int or a char
	cin >> string_to_convert;
	
	if (string_to_convert[0] >= '0' && string_to_convert[0]<='9')
	{
		cout << (char) atoi(string_to_convert.c_str());
	}
	else
	{
		cout << (int) string_to_convert[0];
	}
	return 0;
}
I already posted a working demo that doesn't use C-style casts or result in undefined behavior if the string is empty ;)
Last edited on
Thanks guys, I'll look more into this.

@LB

That's a whole lot of new shiny things you got there (my programming course started a week ago), I'll look more into those, thanks :)
The user wants to know the encoding for the newline character, and hits enter.

std::cin.peek() / std::cin.get() would work.
Also, is there any particular reason you're not using a namespace?

You're all writing using the std::cin format (it's the std:: part I'm curious about), instead of using namespace std; and then just cin etc.
> (it's the std:: part I'm curious about), instead of using namespace std; and then just cin etc.

See: http://www.parashift.com/c++-faq-lite/using-namespace-std.html

This is not an appropriate programming exercise for C++ 101.
With std::cin.peek(), something along these lines:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <iostream>
#include <cctype>
#include <limits>
#include <locale>
#include <stdexcept>

int main()
{
    /************************************************************
    try
    {
        std::cin.imbue( std::locale( "en_US.UTF-8" ) ) ; // note: locale name is implementation specific
    }
    catch( const std::runtime_error& )
    {
        std::cerr << "*** error: failed to imbue locale with ASCII encoding\n" ;
        return 1 ;
    }
    ***************************************************************/

    std::cout << "Input a number to learn the ASCII character of that number,\n"
                 "    or a character to learn the encoding of that character: ";

    using int_type = std::char_traits<char>::int_type ;
    int_type peek ;
    if( ( peek = std::cin.peek() ) != std::char_traits<char>::eof() ) // if something was entered
    {
        if( std::isdigit(peek) || peek == '+' || peek == '-' )
        {
                int_type number ;
                if( std::cin >> number )
                {
                    if( number > std::numeric_limits<char>::max() || number < std::numeric_limits<char>::min() )
                        std::cout << "There is no character with encoding " << number << '\n' ;

                    else if( std::isprint(number) )
                        std::cout << "The character with encoding " << number << " is: '" << char(number) << "'\n" ;

                    else
                        std::cout << "The character with encoding " << number << " is not printable\n" ;

                    if( number >= 0 && number < 10 )
                        std::cout << "The encoding for character '" << number << "' is: " << '0' + number << '\n' ;
                }
                else std::cout << "The encoding for character '" << char(peek) << "' is: " << peek << '\n' ;
        }
        else
        {
            std::cout << "The encoding " ;
            if( std::isprint(peek) ) std::cout << " for character '" << char(peek) << "' " ;
            std::cout << "is: " << peek << '\n' ;
        }
    }
}
Okay, that makes sense, thanks :)

What do you mean this is not an appropriate exercise?
I'd be fine if I only had to do one of the two parts (ie character to number, or the other way around), just curious if I could successfully create a program that did both.
You can create a program that does both, but you need to decide how the user will specify which conversion they want.
@LB, well, that's easy, that's two whiles with breaks and a few if's.

I'd like the program to give a character if a numeric value is entered, and a numeric value if a character is entered.

I'll dig around with comparing strings and whatnot, you all have been most helpful :)
'1' is both a numeric value and a character. Same for '0', '2', '3', ...
Yes, but this is for personal use, so I know what I want :P

And yes, you are right, and I should probably just do it the easy way by asking first. (Although that's not as fun :P)
Did you happen to notice how I handled it? I gave both interpretations.
Yeah, that would be the second option, although I think I'd rather only have one, since I'll most likely know which one I'm looking for.
Pages: 12