Dec 30, 2009 at 12:25pm UTC
i want to read words from a file.
if letters of each word are upper convert to lower.(like A --> a)
if it is not a letter (like:!) convert to " "!" "
example: THE Cat! (i want to convert it to-->) the cat !
Dec 30, 2009 at 1:04pm UTC
You can use tolower() [
http://cplusplus.com/reference/clibrary/cctype/tolower/ ]. A piece of code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <stdio.h>
#include <ctype.h>
char s[100];
int i = 0, n;
int main()
{
FILE *f = fopen ("text.in" ,"r" );
while (!feof(f) )
{
fscanf (f,"%c" , &s[i]);
printf ("%c" , tolower(s[i]));
++ i;
}
fclose(f);
return 0;
}
Last edited on Dec 30, 2009 at 1:04pm UTC
Dec 30, 2009 at 4:24pm UTC
If you write a function object that transforms and accumulates characters, you can then call it for each character using the for_each algorithm. This one sounded like fun so I wrote a little something that does that:
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
#include <iostream>
#include <algorithm>
using namespace std;
struct Copier
{
string result;
void operator ()( char c ) {
char low = tolower( c );
if ( ( 'a' > low || 'z' < low ) && ' ' != low )
{
result += string( " " ) + low + " " ;
}
else
{
result += low;
}
}
};
int main( int argc, char * args[] )
{
string s = "THE Cat!" ;
cout << for_each( s.begin(), s.end(), Copier() ).result;
return 0;
}
It could use a little clean up but it does the trick.
Last edited on Dec 30, 2009 at 6:03pm UTC
Dec 30, 2009 at 6:22pm UTC
@moorecm, it's much more in C++ style than mine. I use to code in C. :)
Dec 30, 2009 at 7:30pm UTC
Why all the extra spaces?