简体   繁体   中英

C++ Need help getting user input for String Frequency Program

Here is my code. I have to write a program that takes user input for a string and displays the frequency of each letter in that string. I get this as an error no matter what I do. What would be the proper way to get user input for this code. Any help would be much appreciated. Thanks::

error: array must be initialized with a brace-enclosed initializer

.

    int main()
{
    string input;
    cin >> input;
   char freq[100] = input;
   int c = 0, count[26] = {0};
   while ( freq[c] != '\0' )
   {

      if ( freq[c] >= 'a' && freq[c] <= 'z' )
         count[freq[c]-'a']++;
      c++;
   }

   for ( c = 0 ; c < 26 ; c++ )
   {
      if( freq[c] != 0 )
         printf("%c occurs %d times in the entered string.\n",c+'a',count[c]);
   }
}

Using std::string is better than old-style char,In fact.you should use those knowledge u r not familiar still.

But if u want to use char now,you can remove variable input.u can change first three lines in main() function to this:

char freq[100];
cin >> freq;

Hey I think I found the answer to my question:

 #include <iostream>
#include <string.h>

using namespace std;

   int main()
{
   string input;
   cout<<"Enter lowercase string: ";
   cin>>input;
   cout<<"Number of characters in string: "<<input.size()<<"\n";
   std::string freq = input;
   int c = 0, count[26] = {0};
   for (std::string::size_type i = 0; i < input.size(); i++) 
   {

      if ( freq[i] >= 'a' && freq[i] <= 'z' ){
         count[freq[i]-'a']++;
      }
      c++;
   }


   for ( c = 0 ; c < 26 ; c++ )
   {
      if( count[c] != 0 )
         printf("%c occurs %d times in the entered string.\n",c+'a',count[c]);
   }
}

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