Click here to Skip to main content
15,891,704 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i try this,,
this is wrong?

the message : Segmentation fault (core dumped)

What I have tried:

C++
int n;
	string s;
        cout << "Long string : ";
	cin >> n;
        cout << "String = ";
   	cin >> s;
	string y = s;
	for(int i = 0; i < n; i++)
	{
		for(int j = i+1; j < n; i++)
		{
			if(y[i] > s[j])
			{
				s[i] = s[j];
				s[j] = y[i];
			}
		}
return 0;
	}
Posted
Updated 26-Jul-18 22:15pm

You know, the C++ programming language features a Standard Library:
C++
#include <iostream>
#include <algorithm>
using namespace std;

int main()
{
  string s;
  cout << "please enter a string: \n";
  cin >> s;
  auto it = min_element( s.cbegin(), s.cend());
  
  if ( it != s.cend())
    cout << "the smallest letter in the string is '" << *it << "'" << endl;
}
 
Share this answer
 
Why do you think you need two nested loops? Particularly when you increment i in both of them instead of i in one, and j in the other?

Instead of a nested loop, think how you would do it manually:
You would start with an empty "lowest" value (so set it to the biggest possible - then all the others are smaller than it) and you would look at each character in the string once, comparing it against the current "lowest".
If it's the same or bigger, you'd ignore it.
Otherwise, you'd set the "lowest" to the current value.

After the loop, the "lowest" is the smallest letter.

So why run nested loops?
 
Share this answer
 
There is another error besides the already mentioned one of incrementing i instead of j in the inner loop:
You are accessing the characters of the strings up to the index n. That won't work if n is greater then the length of the strings.

Both errors result in out of bound accesses (accessing characters out of the memory used by the strings) which result in undefined behaviour or - in the worst case as here - segmentation faults.

Instead of letting the user enter the value for n, use the length of the entered string:
C++
int n = s.length();
Use that to search for the smallest letter as suggested in solution 1.
 
Share this answer
 

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