Я работаю над упражнением из Accelerated C ++:
Напишите программу, чтобы подсчитать, сколько раз каждое отдельное слово появляется в его входе.
Вот мой код:
#include <iostream>
#include <string>
#include <vector>
int main()
{
// Ask for
// and read the input words
std::cout << "Please input your words: " << std::endl;
std::vector<std::string> word_input;
std::string word;
int count = 0;
while (std::cin >> word)
{
word_input.push_back(word);
++count;
}
// Compare the input words
// and output the times of every word compared only with all the words
/***** I think this loop is causing the problem ******/
for (int i = 0; i != count; ++i)
{
int time = 0;
for (int j = 0; j != count; ++j)
{
if (word_input[i] == word_input[j])
++time;
else
break;
}
std::cout << "The time of "
<< word_input[i]
<< " is: "
<< time
<< std::endl;
}
return 0;
}
Если вы скомпилируете и запустите эту программу, вы увидите:
Please input your words:
И я введу следующее:
good good is good
EOF
Затем он показывает:
The time of good is: 2
The time of good is: 2
The time of is is: 0
The time of good is: 2
Мой ожидаемый результат:
The time of good is: 3
The time of is is: 1
Я не хочу использовать карту, потому что у меня нетузнал, что еще.
Что является причиной этого неожиданного поведения, и как я могу это исправить?