Note that there are some explanatory texts on larger screens.

plurals
  1. POFunction to count all characters in a string - C++
    primarykey
    data
    text
    <p>I want to write a functioin in C++, which counts all characters in a string.# I have a string called input, in which the user of the program can enter a sentence, the letters that are important I stored in a string alphabet like this:</p> <pre><code>string alphabet {"ABCDEFGHIJKLMNOPQRSTUVWXYZ"}; </code></pre> <p>and a vector that is used to store the frequency of occurrence of the letters, e.g. A is located on place 0, B on place 0, and so on.</p> <pre><code>vector&lt;long&gt; letterCount (26); </code></pre> <p>I have written the function like I think it should work, and it seems that it is able to figure out the occurences of the characters but after that this figure is multiplied by the place of the letter in the alphabet. Here is the function:</p> <pre><code>long countLetters(int&amp; p) { for(int i = 0; i &lt; alphabet.size(); ++i) { for(long j = 0; j &lt; count(input.begin(), input.end(), alphabet.at(i)) { countLetters.at(i)++; } } return letterCount.at(p); } </code></pre> <p>For example, if the input is "HELLO" the programs puts out:</p> <pre><code>E : 5 H : 8 L : 24 O : 15 </code></pre> <p>So you see, for example the letter 'L' is contained two times in the string, but the result for 'L' is 24, because 'L' is at place 12 in the alphabet.</p> <p>Please help, if you realize what my problem is.</p> <p>EDIT: I've found a way that works, at least partially:</p> <pre><code>long countLetters(int&amp; p) { for(size_t i = 0; i &lt; input.length(); ++i) { for(size_t j = 0; j &lt; alphabet.length(); ++j) { letterCount.at(j) = count(input.begin(), input.end(), alphabet.at(j)); } } return letterCount.at(p); } </code></pre> <p>But when entering two or more words the function only figures out the letter-occurences in the first word. How do I analyze more words?</p> <p>EDIT: before I had <code>cin &gt;&gt; input</code> but <code>getline(cin, input);</code> is right.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload