files

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 !

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
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
@moorecm, it's much more in C++ style than mine. I use to code in C. :)
Why all the extra spaces?
Topic archived. No new replies allowed.