gpt4 book ai didi

C++程序——输入文本流

转载 作者:太空宇宙 更新时间:2023-11-04 13:03:46 26 4
gpt4 key购买 nike

我是 C++ 的新手,我得到了一个示例程序,该程序应该能够计算给定输入文本流中每个可打印非空白字符的出现次数。

显然,我打算用命令参数做一些事情,但是我试过了,但没有得到任何输出。

程序如下:

字符计数器.h

#pragma once
#include <iostream>

class CharacterCounter
{
private:
int fTotalNumberOfCharacters;
int fCharacterCounts[256];

public:
CharacterCounter();

void count( unsigned char aCharacter );

friend std::ostream& operator<<( std::ostream& aOStream,
const CharacterCounter& aCharacterCounter );
};

CharacterCounter.cpp:

#include "CharacterCounter.h"

using namespace std;

CharacterCounter::CharacterCounter(): fTotalNumberOfCharacters( 0 ),
fCharacterCounts()
{}

void CharacterCounter::count( unsigned char aCharacter )
{
fCharacterCounts[aCharacter]++;
fTotalNumberOfCharacters++;
}

ostream& operator<<( ostream& aOStream, const CharacterCounter& aCharacterCounter )
{
aOStream << "Character counts for "
<< aCharacterCounter.fTotalNumberOfCharacters << " characters:"<< endl;

for ( int i = 0; i < 256; i++ )
{
if ( aCharacterCounter.fCharacterCounts[i] != 0 )
{
aOStream << (char)i << ":\t" << aCharacterCounter.fCharacterCounts[i] << endl;
}
}

return aOStream;
}

主要.cpp:

#include "CharacterCounter.h"

using namespace std;

int main()
{
CharacterCounter lCounter;

unsigned char lChar;

while ( cin >> lChar )
{
lCounter.count( lChar );
}

cout << lCounter;

return 0;
}

所以,基本上我要问的是如何修改这个程序,或者让它接受一串文本(或类似的东西)并计算每个字符的出现次数?

最佳答案

您可以使用 std::getline 允许从 std::cin 输入一行,然后以类似于您已有的方式处理它。为简单起见,我:

#include <iostream>
#include <string>
#include <map>

int main() {
std::map<char, size_t> count;

std::string s;
std::getline(std::cin, s);

for (char i : s)
{
++count[i];
}

for (auto i : count)
{
std::cout << i.first << " : " << i.second << std::endl;
}
}

在线here

关于C++程序——输入文本流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43200147/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com