简体   繁体   English

C++ 需要帮助获取字符串频率程序的用户输入

[英]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.使用std::string比旧式char好,事实上。你应该使用那些还不熟悉的知识u r。

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,你可以删除变量 input。你可以将 main() function 中的前三行更改为:

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]);
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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