我有一个向量vec(256,0),用于记录输入文件中的字符类型及其频率。因此,给定3 A,我的vec [65]将保持3的值。我正在尝试将输出文件写入总计数非空字符,然后是ascii字符和出现频率。
int count = 0;
for (int i = 0; i < 256; i++)
if (vec[i] != 0) // if not 0 count it
count++;
// print the count as the first char in output file
outfile << count;
for (int i = 0; i < 256; i++)
if (vec[i] != 0)
outfile << (char) i << vec[i];
给出输入“a bb c”我想要的是:
4a1b2c1
但我得到的是:
5
1 2a1b2c1
我该怎么做才能解决这个问题?
答案 0 :(得分:0)
我假设您输入了一个换行符和两个空格字符。然后,在五个字符总数之后,您将打印换行符,然后是它出现的次数,然后是空格字符,然后是两个字符,然后是其他字符。
修改强>
我知道您不希望在您的计数中包含换行符和空格字符以及类似的控制字符。然后,当你填充向量时,你必须排除它们。假设您的当前字符位于名为char
的{{1}}变量中,那么您将使用类似
c
答案 1 :(得分:0)
您的输入文件如下所示:“a bb c \ r \ n”而不是“a bb c”。这意味着您有五种字符类型:一个'\ n'(ASCII代码:10),一个'\ n'(ASCII代码:13),两个空格(ASCII代码:32),一个'a',两个'b '字符,一个'c'。所以你的代码工作正常!问题是,当您在输出文件中打印'\ _','\ n'和''时,它们将显示为空格。
如果从输入文件中删除换行符,要将“a bb c”作为输入,输出将为:“4 1a1b2c1”,因为空格的ASCII码小于'a'的ASCII码
答案 2 :(得分:0)
使用这段代码:
int count = 0;
for (int i = 0; i < 256; i++)
if (i != 32 && i != 10 && i != 13) // don't count ' ' (spaces) and other stuff
count += vec[i]; //(not all vec[i] values are 1, 98 for instance is 2 (bb))
cout << count;
for (int i = 0; i < 256; i++)
if (i != 32 && i != 10 && i != 13 && vec[i] != 0)
cout << (char) i << vec[i];
答案 3 :(得分:0)
我建议使用地图存储计数。
#include <map>
#include <iostream>
std::map<char, size_t> histogram(std::string const& input)
{
std::map<char, size_t> freq;
for (auto ch : input)
freq[ch]++;
return freq;
}
int main()
{
std::string input = "hello world (or read this from a large file";
auto frequencies = histogram(input);
for (auto& entry : frequencies)
std::cout << "'" << entry.first << "': " << entry.second << "\n";
}
打印
' ': 8
'(': 1
'a': 3
'd': 2
'e': 4
'f': 2
'g': 1
'h': 2
'i': 2
'l': 5
'm': 1
'o': 4
'r': 5
's': 1
't': 1
'w': 1
哦,对于unprintables,
std::cout << "char: 0x" << std::setw(2) << std::ios::hex << entry.first;
为ASCII 7等获得0x07
会很高兴。