简体   繁体   中英

C++ “Same Letter” code doesn't work properly

#include <iostream>
#include <string>

using namespace std;

static char sentence[100];

void sameletter(char sentence[100])
{
    int meter=0;
    char letter;
    cout<<"Enter the letter you want to find in this sentence : ";
    cin>>letter;
    for(int i=0; sentence[i] != '\0'; i++)
    {
        if(sentence[i]==letter)
        {
            meter++;
        }
    }
    cout<<letter<<" letter used "<<meter<<" time(s)."<<endl;
}


int main()
{
cout<<"Enter Sentence : ";
cin>>sentence[100];
gets(sentence);
sameletter(sentence);
}

This is code i wrote. But for some reason it never includes the first letter to the end result. For example lets say i write "We love stack overflow" and i wanted how many times this sentence has the letter "w" so i hit w and it only shows: "w letter used 1 many time(s)." instead of 2. other letters like "o" works perfectly so it's only a problem about the first letter:/ can someone help me about it?

Thanks !

This line:

cin >> sentence[100];

will read a single character into the 100 th index of sentence , which invokes underfined behavior.

Also, gets has been removed from c++ , and you should no longer use it.

Instead, you should use getline :

int main()
{
  std::cout<<"Enter Sentence : ";
  std::getline(std::cin, sentence);
  sameletter(sentence);
}

Also, avoid using namespace std; , it's bad practice.

There's no reason for sentence to be static , or global.

Also, you could just use std::string , instead of char arrays. It will make your life easier. eg your loop could be replaced by an algorithm:

int meter = std::count_if(sentence.begin(), sentence.end(), 
              [=] (unsigned char c) { 
                return std::tolower(c) == std::tolower(letter);
            });

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