#include <iostream>
#include <cstdlib>
#include <cctype>
#include <cmath>
#include <string>
#include <iomanip>
#include <fstream>
#include <stdio.h>
using namespace std;
int main()
{
ifstream file;
string filename;
char character;
int letters[153] = {};
cout << "Enter text file name: ";
cin >> filename;
file.open(filename.c_str());
if (! file.is_open())
{
cout << "Error opening file. Check file name. Exiting program." << endl;
exit(0);
}
while (file.peek() != EOF)
{
file >> character;
if(!file.fail())
{
letters[static_cast<int>(character)]++;
}
}
for (int i = 0; i <= 153; i++)
{
if (letters[i] > 0)
{
cout << static_cast<char>(i) << " " << letters[i] << endl;
}
}
exit(0);
}
#endif
大家好,我現在的代碼統計文本文件中每個字母的頻率。但是,它不計算空格的數量。有沒有簡單的方法來打印.txt文件中的空格的數量?在C++中打印出一個文本文件中的空格
另外,當我試圖訪問一個矢量項目時,我怎麼會遇到seg錯誤? 例如,如果我使用:
COUT < < 「」 +字母[I] < < ENDL ;,它顯示一個段錯誤。有任何想法嗎?
非常感謝。
請注意,您的矢量的有效位置是'字母[0]'到'字母[152]'。 –
@WhozCraig:除了你只是使用一個數組,因爲使用'unordered_map'將小整數值映射到整數是過量的。 –
在for循環中,你說「我<= 153」,而你可能想要「我<153」。 for-loops的標準是在條件中使用「<」。 –