简体   繁体   中英

C++ How do I read in a file, convert each word to lower case and then cout each word?

I am having trouble getting started with a program. I need to read in each word from a file, then convert it to lower case. I would like to std::cout each word after I find it. I assume I need to use Cstr() some how. I am guessing I should use something like

ofs.open(infile.c_str());

but how to lower case?

string[i] = tolower(string[i]);

then,

std::cout << string[i];

Thanks for the help.

Here is a complete solution:

#include <ctype.h>
#include <iterator>
#include <algorithm>
#include <fstream>
#include <iostream>

char my_tolower(unsigned char c)
{
    return tolower(c);
}

int main(int ac, char* av[]) {
    std::transform(std::istreambuf_iterator<char>(
        ac == 1? std::cin.rdbuf(): std::ifstream(av[1]).rdbuf()),
        std::istreambuf_iterator<char>(),
        std::ostreambuf_iterator<char>(std::cout), &my_tolower);
}
int main()
{

    ofstream of("xyz.txt");

    clrscr();
    ifstream inf;
    char line;
    inf.open("abc.txt");
    int count=0;
    while(!inf.eof())
    {
        inf.get(line);
        if(line>=65 && line<=123)
        {
            cout<<line;
            line=line-32;
            of<<line;
            count++;
            cout<<line;
        }
    }
    cout<<count;
    getch();
    return 0;
}

I found the answer to my own question. I really didn't want to use transform, but that does work as well. If anyone else stumbles across this here is how I figured it out...

#include <iostream>
#include <string>
#include <fstream>

int main()
{
std::ifstream theFile;
theFile.open("test.txt");
std::string theLine;
while (!theFile.eof())
{
  theFile >> theLine;       
  for (size_t j=0; j< theLine.length(); ++j)
  {
    theLine[j] = tolower(theLine[j]);
  }
  std::cout<<theLine<<std::endl;
     } 

 return 0;
}

First of all, unless this is something like a homework assignment, it's probably easier to process one character at a time rather than one word at a time.

Yes, you have pretty much the right idea for converting to lower case, with the minor detail that you normally want to cast the input to unsigned char before passing it to tolower .

Personally, I'd avoid doing explicit input and output, and instead do a std::transform with a pair of istream_iterator s and an ostream_iterator for the result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM