C++如何读取文件,将每个单词转换为小写,然后输出每个单词?
我在开始使用程序时遇到了问题。我需要从文件中读取每个单词,然后将其转换为小写。我想在找到它之后将std :: cout添加到每个单词中。我假设我需要使用Cstr()一些方法。我猜我应该使用类似C++如何读取文件,将每个单词转换为小写,然后输出每个单词?
ofs.open(infile.c_str());
但如何小写?
string[i] = tolower(string[i]);
然后,
std::cout << string[i];
感谢您的帮助。
首先,除非这是一项家庭作业,否则一次处理一个字符而不是一次处理一个字可能更容易。
是的,你有几乎正确的想法转换为小写,你通常希望投入到unsigned char
的小细节,然后传递给tolower
。
就个人而言,我会避免做明确的输入和输出,而是做一个std::transform
与一对istream_iterator
s和一个ostream_iterator
的结果。
注意可能的复制你当使用'std :: istream_iterator
这里是一个完整的解决方案:
#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);
}
我找到了答案,以我自己的问题。我真的不想使用转换,但这也可以。如果任何人碰到这个别人绊倒这里是如何我想它了...
#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;
}
http://*.com/questions/313970/stl-string-to-lower-case – 2012-03-18 21:40:25