Click here to Skip to main content
15,897,273 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to print the duplicate element in a given string. The following is my code:

I am getting segmentation error.

Test case=> if the input is "hey this this is me" then the program has to print "this".

What I have tried:

int main(){
	 char str[30];
	 int n,i;
	 cout<<"enter the size";
	 cin>>n;
	 cout<<"Enter the words";
	 int a[30];
	 for(i=0;i<n;i++)
	 	{
	 		cin<<str[i];

	 	}
	for(i=0;i<n;i++)
	{
		a[str[i]]+=1;
	}
	for(i=0;i<n;i++)
	{
		if(a[i]>1)
		{
			cout<<str[i];
		}
	}
}
Posted
Updated 25-Jul-17 10:09am

Um... Are you sure you wanted this?
cin<<str[i];

Because I suspect you might have wanted this:
cin>>str[i];

Then...this is wrong:
a[str[i]]+=1;
Because regardless of the value of i, str[i] will be a character, which means that the space character will have a value of 32, and alphabetics a lot higher than that: ASCII Table[^] Since your array a only has 30 elements, no character you can type will result in a good index value into a

Then there is the task: which even well and truly sorted out, that code isn't going to get close to - what you need to do is pass through your string, and identify each word start and end. You can then use that info to identify repeated words.
Try it on paper first, and when you have a good algorithm worked out, then you can try converting that to something a computer can understand. At the moment, you are rushing into code without properly thinking about the job first - and that just doesn't work well for anything more complex than "Hello World!"
 
Share this answer
 
v2
Hey man, it's C++
C++
#include <string>
#include <iostream>
#include <sstream>
#include <set>
using namespace std;

int main()
{
  string line;
  cout << "please, enter the sentence" << endl;
  getline(cin, line);

  istringstream iss(line);
  set<string> wordset;
  string word;

  while ((iss >> word))
  {
    if ( wordset.find(word) == wordset.end() )
      wordset.insert(word);
    else
      cout << word << endl; // print out the duplicate word
  }
}
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900