Reputation: 227
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.
Upvotes: 0
Views: 10503
Reputation: 7
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;
}
Upvotes: 1
Reputation: 227
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;
}
Upvotes: 1
Reputation: 153955
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);
}
Upvotes: 2
Reputation: 490348
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.
Upvotes: 0