Space ascii code

Jun 8, 2014 at 6:05am
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;	
	}
Jun 8, 2014 at 6:24am
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
Jun 8, 2014 at 8:07am
Thank you,
But when i used check ascii code instead isspace(ch) , What i do?
Jun 8, 2014 at 8:26am
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  ) { /* .... */ }
Jun 8, 2014 at 8:33am
Thank you,
But I want check ascii code(32).
Last edited on Jun 8, 2014 at 8:36am
Jun 8, 2014 at 8:48am
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 Jun 8, 2014 at 8:53am
Jun 8, 2014 at 8:49am
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.