0
#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 !

Armads
  • 1
  • 1

1 Answers1

3

This line:

cin >> sentence[100];

will read a single character into the 100th 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. e.g. 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);
            });
cigien
  • 57,834
  • 11
  • 73
  • 112
  • And that char array being static really serves no purpose. In general, avoid declaring static variables, especially when it serves no purpose. – ChemiCalChems May 13 '20 at 21:32
  • 1
    @ChemiCalChems `static` changes behaviour at global scope. In this usage the variable is bound to that one translation unit, so it does do something. I don't see any point to it being global, though. – user4581301 May 13 '20 at 21:35
  • BTW, the searches for letters are case sensitive. For example, 'W' != 'w'. One solution is to copy the sentence, then `transform` the sentence to all lower case. – Thomas Matthews May 13 '20 at 21:56