I am in a c++ problem solving course, and the following question is from past year students assignment and i am trying to solve them for my own practice.
the question states that the user should enter a number and my program should search a string and if the letters are repeated as that number i should show the repeated letter for ex. string (school to home)
user input : 2
program should show 'h' was repeated 2 times.
that was my try below but it is not working properly.
any suggestions ?.
#include <iostream>
#include <stdio.h>
usingnamespace std;
void main()
{
char x[1000];
int t;
int pos=0,pos2=0;
int count=1;
cout<<"please enter a string : ";
gets_s (x);
cout<<"please enter number to show repeated letters : ";
cin>>t;
int f=0;
while (1)
{
if (x[f]=='\0')
{
pos=f;
break;
}
f++;
}
int i;
for (i = 0; i < pos; i++)
{
for (int j = 0; j < pos; j++)
{
if (x[j]==x[i])
{
++count;
}
}
if (count==t)
{
cout<<x[i];
break;
}
}
}
since i am still a beginner and didn't take except the 2 libraries above and no functions yet i can understand some of what you did but is the problem in my last if statement ??
#include <iostream>
//#include <cstdio>
int main() // It is int main(), not void main(). Another valid one is int main(int argc, char **argv).
{
std::string x; // It works exactly like a char[], but it can be any size.
int t;
// int pos = 0, pos2 = 0; // No need for these
int count = 0;
std::cout << "please enter a string : ";
std::cin >> x;
std::cout << "please enter number to show repeated letters : ";
std::cin >> t;
// int f=0;
// Finds the size, stores in in f. We'll use x.size(); instead.
// while (true)
// {
// if (x[f]=='\0')
// {
// pos=f;
// break;
// }
// f++;
// }
for (int i = 0; i < x.size(); i++)
{
for (int j = 0; j < x.size(); j++)
{
if (x[j] == x[i])
{
++count;
}
}
if (count == t)
{
std::cout << x[i];
// break; // No need to break here.
}
count = 0; // Must reset the counter, we're checking for a new character!
}
return 0; // Return code showing that program ran succesfully!
}