我在開始使用程序時遇到了問題。我需要從文件中讀取每個單詞,然後將其轉換爲小寫。我想在找到它之後將std :: cout添加到每個單詞中。我假設我需要使用Cstr()一些方法。我猜我應該使用類似C++如何讀取文件,將每個單詞轉換爲小寫,然後輸出每個單詞?
ofs.open(infile.c_str());
但如何小寫?
string[i] = tolower(string[i]);
然後,
std::cout << string[i];
感謝您的幫助。
我在開始使用程序時遇到了問題。我需要從文件中讀取每個單詞,然後將其轉換爲小寫。我想在找到它之後將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://stackoverflow.com/questions/313970/stl-string-to-lower-case – 2012-03-18 21:40:25