2012-03-18 97 views
0

我在開始使用程序時遇到了問題。我需要從文件中讀取每個單詞,然後將其轉換爲小寫。我想在找到它之後將std :: cout添加到每個單詞中。我假設我需要使用Cstr()一些方法。我猜我應該使用類似C++如何讀取文件,將每個單詞轉換爲小寫,然後輸出每個單詞?

ofs.open(infile.c_str()); 

但如何小寫?

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

然後,

std::cout << string[i]; 

感謝您的幫助。

+0

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

回答

0

首先,除非這是一項家庭作業,否則一次處理一個字符而不是一次處理一個字可能更容易。

是的,你有幾乎正確的想法轉換爲小寫,你通常希望投入到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

2

這裏是一個完整的解決方案:

#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

1

我找到了答案,以我自己的問題。我真的不想使用轉換,但這也可以。如果任何人碰到這個別人絆倒這裏是如何我想它了...

#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; 
} 
相關問題