Splitting string and assembly issues

I can't seem to get my spaces to show up in my text and the numbers and letters are not appearing in the correct location. I thought the array was supposed to keep track of the locations of each section but the output is not in order. How do I fix this?

#include <iostream>
#include <cctype>
#include <string>

using namespace std;

int main()
{

string text, numbers, alphabet, spaces;

cout << "Enter Phrase: " << endl;
getline(cin, text);
//int j;(used later to count number of spaces)
for(int i=0; i<=text.length();i++)
{
if(isdigit(text[i]))
{
numbers+=text[i];
cout << text[i];
}
if(isalpha(text[i]))
{
alphabet+=text[i];
}
if(isspace(text[i]))
{
spaces+=text[i];//+j++(to count the number of spaces)
}
}
cout << "Numbers in the string: " << endl;
cout << numbers << endl;
cout << "Alphabets in the string: " << endl;
cout << alphabet << endl;
cout << "Spaces in the string: " << endl;
cout << j << endl;

cout << alphabet+numbers+spaces;//having issues here
return 0;
}
Try this on for size. I wouldn't recommend handing it in as is though without being able to explain line 16 and what you would need to do so program actually only counts characters (a-z) and (A-Z).

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

using namespace std;

 int main() {
	string text;
	int Numbs, Chars, Spaces;
	
	Numbs = Chars = Spaces = 0;	
	cout << "\nEnter Phrase: ";
	getline(cin, text);
	cout << "\n\t";
	
	if ( text.length () ) {
		for ( char ch : text ) {
			if ( isdigit (ch) )
				Numbs++;
			else if ( ch == ' ' )
				Spaces++;
			else
				Chars++;
		}
		
		cout << Chars << " characters, " << Spaces << " spaces, "
			 << Numbs << " digits" << endl;
	}
 
	return 0;
 } 

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
38
39
40
41
#include <iostream>
#include <string>

using namespace std;

int main()
{
	string text;
	int numbers = 0, alphabet = 0, spaces = 0;
	
	cout << "Enter Phrase:| ";
	getline(cin, text);
	//int j;(used later to count number of spaces)
	for (int i = 0; i <= text.length(); i++)
	{
		if (isdigit(text[i]))
		{
			numbers++;
		}
		if(isalpha(text[i]))
		{
			alphabet++;
		}
		if ((text[i] == ' '))
		{
			spaces++;
		}
	}

	cout << "\nNumbers in the string: " << endl;
	cout << numbers << endl;
	cout << "Alphabets in the string: " << endl;
	cout << alphabet << endl;
	cout << "Spaces in the string: " << endl;
	cout << spaces << endl;

	cout << endl << endl;
	system("pause");
	return 0;
	
}
Topic archived. No new replies allowed.