-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);
}
4

2 回答 2

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;
}
于 2013-02-23T20:02:07.910 回答
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);
}
于 2013-02-23T19:37:35.730 回答