what's the wrong with this code?

what's the wrong with this code? I'm trying to cut this one line input string into substrings but when I started with the first substring it didn't work,help please!!
CODE:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <string>
using namespace std;
int main()
{
	string Students;
	string S1;
	getline(cin,Students);
	Students="[12001,Ahmed Hassan,(CSE121,HUM001);12002,Aly Hamed,(CSE121);12003,Omar Mohammed,(Math002)]";
	for (int i=0;i<Students.length();i++)
	{
	  if (i==';')
	  {
		  string S1 =Students.substr(0,i-1);
		  Students.erase(0,i);
	  }
	  
	}
	cout<<S1<<endl;
	system("pause");
	return 0;
}
Last edited on
 
if (i==';')


You're comparing the index (i) to a ';'
You want to compare Students[i] to ';'

PLEASE USE CODE TAGS (the <> formatting button) when posting code.
It makes it easier to read your code and also easier to respond to your post.
http://www.cplusplus.com/articles/jEywvCM9/
Hint: You can edit your post, highlight your code and press the <> formatting button.
Thank you,I edited :)
If I don't exactly know the length of the string as the user can enter up to 100 students , how can I split it into arrays or substrings please?
I think you misunderstood my question, I know how to split a string into substrings but I can do this if I only know the length of this string, my question is if I don't know its length and I want to split it into substrings each substring takes from the semi colon to the next one how can I do that?
I can do this if I only know the length of this string

I'm unclear what you don't know the length of. You're already using Students.length().
You can of course get the length of S1 by calling S1.length().
You can get the length of any substring by taking the difference between the locations of the semicolons.

However, there's a problem with your loop.

Line 14: You isolate the first subsctring to S1 and then erase those characters from Students.
That works fine on the first iteration. On subsequent iterations, i is now pointing to the wrong place (36), so on the second iteration you're pointing to the middle of the third student.
1
2
3
0....+....1....+....2....+....3....+....4....+....5....+
12002,Aly Hamed,(CSE121);12003,Omar Mohammed,(Math002)]
____________________________________^


Suggestion: Don't do the erase. Instead keep track of where the previous ; was and continue searching from there.

Line 16: S1 goes out of scope here.

Line 19: Your cout is in the wrong place. It should be after line 15. line 19 is displaying the S1 declared at 7, which is empty.
Last edited on
Thanks a lot for your help :)
Hi,

Just for future reference, please use the title of your posts to provide a brief description of your problem. People are more likely to read and reply to posts where the author did so.
Topic archived. No new replies allowed.