注册 登录
编程论坛 C++教室

c++输入输出流求解

创世乔丹 发布于 2021-11-22 15:20, 1313 次点击
在words.txt文件中包含了87314个单词,编写C++程序从words文件中读取单词,并输出重复字母对最多的单词,将第一个最多重复字母对的单词写入newwords.txt文件中。例如tooth这个单词有一个重复字母对,committee有三个重复字母对。
要求写注释。
2 回复
#2
rjsp2021-11-23 07:59
听不懂

什么叫“单词”,比如“I'm”算一个单词还是两个?
“例如tooth这个单词有一个重复字母对”------ 你的意思是只有相邻的相同字母才算是“重复字母对”?
例如“ooop”“www”算几个“重复字母对”?
#3
rjsp2021-11-23 08:16
程序代码:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int foo( const std::string& word )
{
    int count = 0;
    for( const char* p=word.c_str(); *p; ++p )
        count += *p == *(p+1);
    return count;
}

int main( void )
{
    int count_max = -1;
    string word_max;

    ifstream fin( "words.txt" );
    for( string word; fin>>word; )
    {
        int count = foo(word);
        if( count_max < count )
        {
            count_max = count;
            word_max = word;
        }
    }

    ofstream fout( "newwords.txt" );
    fout << word_max;
}
1