Space ascii code

Hi,
I want get number while user insert space with ascii code(32)
What i do?
The below code doesn't work.
1
2
3
4
5
6
7
	char ch;
	cin>>ch;
	while (32 !=(int)ch)
	{
		cout<<(int)ch;
		cin>>ch;	
	}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <cctype>

int main()
{
    char ch ;
    
    // get() - unformatted input (does not skip leading whitespace)
    // http://www.cplusplus.com/reference/istream/istream/get/
    // std::isspace() - http://www.cplusplus.com/reference/cctype/isspace/ 
    while( std::cin.get(ch) && !std::isspace(ch) ) std::cout << ch << ' ' << int(ch) << '\n' ;
    
    // or for formatted input with >>
    std::cin >> std::noskipws ; // http://www.cplusplus.com/reference/ios/noskipws/
    while( std::cin >> ch && !std::isspace(ch) ) std::cout << ch << ' ' << int(ch) << '\n' ;
}

http://coliru.stacked-crooked.com/a/982e9cd5cd81ca4b
Thank you,
But when i used check ascii code instead isspace(ch) , What i do?
To read characters one by one; break out of the loop if a space is encountered:

1
2
3
const int SPACE = ' ' ; // code-point for space
char ch ;
while( std::cin.get(ch) && ch != SPACE  ) { /* .... */ }
Thank you,
But I want check ascii code(32).
Last edited on
Use ch != 32 instead.
But do so only if you are required to do that. Using character codes directly is a bad style and can lead to different problems
Edit: JLBorges provided a workaround handling both style problem and different problems (your program will either work or crash with assertion failure noticing you that you just avoided serious problem)
Last edited on
1
2
3
4
const int SPACE = 32 ; // hard-coded code-point for space (32)
assert( SPACE == ' ' ) ; // assert that the assumption holds: code-point for space is 32 
char ch ;
while( std::cin.get(ch) && ch != SPACE  ) { /* .... */ }
Topic archived. No new replies allowed.