A problem with an array of C-Strings

I've go quite a strange problem with an array of strings. This is a program made to sort an array or strings in ascending order (ie the first character of the array if checked in each case).

The program:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include<iostream>
#include<cstring>

using namespace std;

int main ()
{

int n;
char str[10][80],temp[80];
cout<<" enter the no. of strings \n\n";
cin>>n;

for(int i=0;i<n;i++)
cin.getline(str[i],79);

for( int i=0;i<n;i++)
{for( int j=i+1;j<n;j++)

 if(strcmp(str[i],str[j])>0)
 strcpy(temp,str[i]);
 strcpy(str[i],str[j]);
 strcpy(str[j],temp);
}

for(int k=0;k<n;k++)
{
cout<<" ";
cout<<str[k];
}
}


Yes, the code is ugly and unindented, but thats not the point. The problem is that it prints out trash and sometimes throws errors. Any ideas?

Disregard any syntax errors.
1
2
3
4
5
 if(strcmp(str[i],str[j])>0){
     strcpy(temp,str[i]);
     strcpy(str[i],str[j]);
     strcpy(str[j],temp);
 }

See what happens when you don't indent?
My apologies, that was a silly mistake, but that still doesnt solve the problem.

I always indent my code though, this is just some code my friend showed me, and he has a pretty horrible coding style.
Last edited on
I think you are reading newline as well when entering n.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include<iostream>
#include<cstring>

using namespace std;

int main ()
{

	int n;
	char str[10][80],temp[80];
	cout<<" enter the no. of strings \n\n";
	cin>>n;
	cin.ignore(1); // This will ignore the newline

	for(int i=0;i<n;i++)
		cin.getline(str[i],79);

	for( i=0;i<n;i++)
	{
		for( int j=i+1;j<n;j++)
		{
			if(strcmp(str[i],str[j])>0)
			{
			 strcpy(temp,str[i]);
			 strcpy(str[i],str[j]);
			 strcpy(str[j],temp);
			}
		}
	}

	for(int k=0;k<n;k++)
	{
		cout<<" ";
		cout<<str[k];
	}
	return 0;
}
OMFG that was such a stupid mistake. Thanks for the help, the program works perfectly now.
Topic archived. No new replies allowed.