简体   繁体   中英

How to extract letters from separate lines and do something with them?

I am writing a program in c++ that takes in letters and prints them out. So, something like:

A AAAAA

B BBBBB

C CCCCC

I used a for loop to go through all letters from input, extract each letter using substr and then cout the letter. Now, I need to count how many A's are there in the first vertical position (bold letters), which is in this case one and calculate the percentage of A's in the vertical column. How do I do that? I am confused and any help is appreciated!

Thanks!

this is the code:

while(s < numberL) 
{
  sp = word;
  s++
  for (int i = 0; i < correct.length(); i++)
  {
      if(answer.at(i) == correct.at(i)) 
      {
           word = answer.substr(i,1); 
           cout << word;
      }
      if ( answer.at(i) != correct.at(i) && answer.at(i) != '?')
      { 
           word = answer.substr(i,1);
           cout << word;
      }
      if (answer.at(i) == '?') 
      {
           word = answer.substr(i,1);
           cout << word; 
      }

   }
  }

Well, the easiest way to use this is by using a character frequency array . Basically, make an integer array of size 26 (or any numeric type you want - depends on how many of each letter you expect to have) and simply keep track of how many of each character you have.

So, lets walk through your example.

When you read each line, take the first character and do the following operation: c - 65 in order to convert the upper case letter A to represent 0, B to represent 1, C as 2, etc. Then, you can simply index into the array and increase the frequency of whichever letter you get. Output the rest of the line.

After doing all of the output, go back through the array again and print out the percentages found.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM