Click here to Skip to main content
15,891,253 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Following piece of code reads from a file and then prints output on the screen.

C++
#define _CRT_SECURE_NO_WARNINGS
#include "stdafx.h"
int main ()
{
	char c;
	int i;
	for (i=0; (c!=EOF); ++i)
	{
		c=getchar();
		printf("%c",c);
	}
} 


When I execute .exe file and redirect the input to ReadMe.txt and output to tmp.txt by giving following command in cmd:
file.exe < ReadMe.txt > tmp.txt


program prints a funny character at the end of the file i.e., ÿ. To avoid this I want to mention the range of valid character in the loop which means program should terminate if any character outside this range hits the loop iteration. I know,

Letters range::- 'a' to 'z' , 'A' to 'Z'
(c<'A') && (c>'Z') && (c<'a') && (c>'z')

Digits range::- '0' to '9'
(c<'0') && (c>'9')


Now I want the range of other characters i.e., ~!@#$%^&*()-+=_[]{}\|:;"'<>,.?/

I was wondering if someone can help me in that.
Posted

1 solution

Not quite what you want: 'A' is less that 'Z' and less than 'a'!

C++
if ( ((c >= 'A') && (c <= 'Z')) || ((c >= 'a') && (c <= 'z')))
   {
   // It's an Alpha
   }

C++
if ((c >= '0') && (c <= '9'))
   {
   // It's an Digit
   }

And you can check for the other print able characters quite easily.
But...
C++
if ((c >= ' ') && (c <= '~'))
   {
   // It's printable.
   }
Might be easier.
 
Share this answer
 
Comments
[no name] 15-Aug-14 8:01am    
Sorry @OriginalGriff, I didn't get what you said. ('A' is less than 'Z') ?
OriginalGriff 15-Aug-14 8:06am    
Oh yes. Characters have an "order" in whatever encoding you use: ASCII, Unicode, even EBCDIC.
For ASCII (and also Unicode, but it's a lot bigger:
http://www.asciitable.com/index/asciifull.gif
For a "standard" text file, you can treat anything below space or above tilde as "unprintable"
[no name] 15-Aug-14 8:19am    
@OriginalGriff , I modified the original code as:

#define _CRT_SECURE_NO_WARNINGS
#include "stdafx.h"

int main ()
{
char c;
int i;
for (i=0; (c!=EOF); ++i)
{
c=getchar();
if ( ((c <= 'A') && (c >= 'Z')) || ((c <= 'a') && (c >= 'z')))
{
c='%';
}
if ((c <= '0') && (c >= '9'))
{
c='%';
}
if ((c <= ' ') && (c >= '~'))
{
c='%';
}
printf("%c",c);
}
}
I'm still not able to get rid of this funny character (ÿ). It still gets printed at the end of output file.
OriginalGriff 15-Aug-14 8:39am    
Um.
Did you read what I wrote, at all?
Is something is not A-Z or a-z, it will never pass your digit check.
Try the last way I showed you, and if it is printable, print it. Otherwise, do nothing.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900