C++如何读取文件,将每个单词转换为小写,然后输出每个单词?

问题描述:

我在开始使用程序时遇到了问题。我需要从文件中读取每个单词,然后将其转换为小写。我想在找到它之后将std :: cout添加到每个单词中。我假设我需要使用Cstr()一些方法。我猜我应该使用类似C++如何读取文件,将每个单词转换为小写,然后输出每个单词?

ofs.open(infile.c_str()); 

但如何小写?

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

然后,

std::cout << string[i]; 

感谢您的帮助。

+0

http://*.com/questions/313970/stl-string-to-lower-case – 2012-03-18 21:40:25

首先,除非这是一项家庭作业,否则一次处理一个字符而不是一次处理一个字可能更容易。

是的,你有几乎正确的想法转换为小写,你通常希望投入到unsigned char的小细节,然后传递给tolower

就个人而言,我会避免做明确的输入和输出,而是做一个std::transform与一对istream_iterator s和一个ostream_iterator的结果。

+0

注意可能的复制你当使用'std :: istream_iterator '时,需要关闭空白的跳过(例如使用'std :: noskipws'),否则所有空格都将被吃掉。特别是对于字符类型,可以通过使用'std :: istreambuf_iterator '(注意额外的'buf')来避免这个问题,并且使代码更加高效。 – 2012-03-18 21:51:14

这里是一个完整的解决方案:

#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); 
} 
+0

你可能想要cctype而不是ctype.h – ipc 2012-03-18 22:00:55

+0

@ipc:对吗?我为什么要?就是这样'tolower()'被放入命名空间'std'中?上面的代码编译并按预期执行。我可以包含''并使用'std :: tolower(c)',但对于这段代码,它确实没有什么不同。 – 2012-03-18 22:14:40

+0

这是因为''不符合C++标准。 – ipc 2012-03-18 22:24:08

我找到了答案,以我自己的问题。我真的不想使用转换,但这也可以。如果任何人碰到这个别人绊倒这里是如何我想它了...

#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; 
}