storing a 2d array with one string & sorting it

sorting a possible 2day array - im trying to sort an array that recieves the user's input for each element. If the input has a "," (comma) in it then i think i want to store the second half of the string (anything to the right of the "," in the second column of the array.

Here's my code so far:

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
#include <iostream>
#include <string>
#include <algorithm>

using namespace std;
int main()
{	
	string words[10, 10];
	cout<< "Enter book name & author (<book name>, <author name>)" << endl;
		for(int i=0;i<=10;i++)
	{
		cin >> words[i];
		char char_list[]=","
		i = strspn(words[i], char_list);
		cin >> words[null, i]
	}

		cout<< "Unorganized List: " << endl;
	int i;
	for(i = 0; i<10; i++)
			cout<<words[i]<<endl;
	sort(words, words + 10);
	cout<< "Organized List: " << endl << endl;
	for(i=0;i<10;i++)
		cout<<words[i]<<endl;
	system("PAUSE");
	return EXIT_SUCCESS;
}


I'm having a little trouble as you can see if you run it but any tips or points in the right direction would be great
I will run through from the top... I can't imagine the number of compile errors your getting now :)

This:
 
string words[10, 10];


is invalid syntax... From your description and your code I assume:

You want the user to input 10 books and authors...

Since there are ten books and two fields of information per book (that is name and author)...

Use this:
 
string words[10][2];


Then for the cin part...
1
2
3
4
5
6
7
for(i=0; i<10; ++i) {
   cout<< "Enter book name & author (<book name>, <author name>)" << endl;
   string bookstring=""; // the string to store (<book name>, <author name>)
   getline(cin, bookstring); // ask the user for their input
   words[i][0] = bookstring.substr(0, bookstring.find(',')-1); // set the book  name
   words[i][1] = bookstring.substr(bookstring.find(',')+1); // set the author name
}


Try that for now...

List of things to look out for in the future:


1.) Invalid syntax (in general)

2.) for() limits you specified a loop of 11 iterations:

 
for(int i=0;i<=10;i++) // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 = 11: array index out of bounds 



- Alan
Last edited on
Don't use cin for string objects. Use getline(cin, str)
Topic archived. No new replies allowed.