Problem with question !!!!!!!!!!

The question is:
Write a program to a string from the user.
Also ask the user to enter a character.
Then find the position of first occurrence of that character in the string and then copy the string from this position to new string.

And that my code:
#include<iostream>
using namespace std;
void main()
{
char x[50]; int ch;
gets(x);
cin>>ch ;
char y[50]; char count;
int j=0;
while(x[j]!='\0')
{
if(x[j]==ch)
{
y[count]=x[j];
count++;
}
j++;
}
for(int k=0; k<count; k++)
{
cout<<y[k];
}
}

something doesn't go well.....
Last edited on
Please try to indent your code and put it within code tags.

Firstly, I do not see any use of the variable count.

Secondly once you find a match of the character in the input string, you should break out of the while loop.
1
2
3
4
5
6
7
8
9
10
11
while(x[j]!='\0')
{
  if(x[j]==ch)
     break;
   j++;
}
int i=j;
for (; x[i] != '\0'; i++) // copy the remaining characters from the matched position
  y[i-j] = x[i];
y[i-j] = '\0';
// now you can output the array 'y'. 

The above code is just to give you an idea and it may contain some bugs.
Thank you for reply but sorry I didn't understand your code and when I try it the output is not what the question want.
How to use code tags: http://www.cplusplus.com/articles/jEywvCM9/

What you have to change is:
1
2
3
4
5
6
7
8
char y[50]; char count = 0; // important!
int cur = 0;
...
if(x[cur]==ch)
..
else
cur++;
...

but there are more ways to do that...
Topic archived. No new replies allowed.