Hi guys, I'm trying to make a program that can read a file, check each 'character', record the frequency of each character, then print the character that is most frequent. I'm also aiming to make this program apply to any character, not just the letters displayed in the text file.
The text file is as follows:
yy
aaa
b
So far I've managed to parse the file and store each sequence of characters into different elements of a vector named list.
Right now I'm trying to access each element of the vector, count the occurrences of each character and compare them. However once I compile the program, I get the error message "string subscript out of range".
I believe the issue lies somewhere within my last 'for' loop because if I change the loop to "(int i = 0; i < size -1; i++)" the error message stops however, as expected, the console only prints the line "ya", completely ignoring b.
Can anyone explain the reason behind this? I'm still fairly new to programming so I apologise if this seems a bit silly.
Also, any tips on how to make this program would also be appreciated, thanks :)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
|
std::vector<std::string> list;
std::ifstream ifile;
ifile.open("test.txt");
std::string charsequence;
char spaces[3]; //array for position of spaces
int position = 0;
if (ifile.fail())
{
std::cout << "Error opening file" << std::endl;
exit(1);
}
std::string line;
while (getline(ifile, line))
{
for (int i = 0; i < line.length(); i++)
{
if (line[i] == ' ')
{
spaces[position] = i;
position++;
}
}
charsequence = line.substr(0, spaces[position]);
list.push_back(line);
}
int size = list.size();
for (int i = 0; i < size; i++)
{
std::string seq = list[i];
char letter = seq[i];
std::cout << letter;
}
|