2013-02-23 42 views
-4

的第一个字母这是我输入txt文件如何大写单词

i like apple and i love to eat apple.are you like to eat apple. 

我要输出这个文件到另一个文本文件,其中一条新线路必须完全停止后插入每个字必须大写,就像我们在php或python中使用Toupper一样。我将如何做到这一点?

这是我做的编码:

inputFile.get(ch); 
while (!inputFile.eof()) 
{ 
    outputFile.put(toupper(ch)); 
    inputFile.get(ch); 
} 
+0

什么错,你没有编码? – Slava 2013-02-23 19:33:39

+2

它的大写每个单词,不仅是单词的第一个字母,其次它不发出新的行后,完全停止输出文件 – Rocket 2013-02-23 19:38:21

+0

什么是fulllstop? – Slava 2013-02-23 20:04:29

回答

1

  • 大写每个单词的第一个字母
  • 插入新行之后.

做:

bool shouldCapitalize = true; 
while (!inputFile.eof()) 
{ 
    if (ch >= 'a' && ch <= 'z') 
    { 
     if (shouldCapitalize) 
      outputFile.put(toupper(ch)); 
     else 
      outputFile.put(ch); 
     shouldCapitalize = false; 
    } 
    else 
    { 
     if (ch == ' ') // before start of word 
      shouldCapitalize = true; 
     outputFile.put(ch); 
    } 
    if (ch == '.') 
    { 
     shouldCapitalize = true; 
     outputFile.put('\n'); 
    } 
    inputFile.get(ch); 
} 
+0

正是这个我想要的 – Rocket 2013-02-23 19:42:14

+0

+1非常好:) – 0x499602D2 2013-02-23 22:15:28

2

更多C++方式:

#include <fstream> 
#include <iterator> 
#include <algorithm> 

class WordUpper { 
public: 
    WordUpper() : m_wasLetter(false) {} 
    char operator()(char c); 

private: 
    bool m_wasLetter; 
}; 

char WordUpper::operator()(char c) 
{ 
    if(isalpha(c)) { 
     if(!m_wasLetter) c = toupper(c); 
     m_wasLetter = true; 
    } else 
     m_wasLetter = false; 

    return c; 
} 

int main() 
{ 
    std::ifstream in("foo.txt"); 
    std::ofstream out("out.txt"); 
    std::transform(std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>(), 
        std::ostreambuf_iterator<char>(out), 
        WordUpper()); 
    return 0; 
}