Copying CString between whitespaces

Hey there.

I've been taking a C++ course for a few weeks now and I'm trying to understand a little bit more about how CString works.

Suppose we take a Cstring that contained name, age, and title. All three of these were separated by a whitespace. And we want to extract the name, age, and title into a cstring of their own.

I'm trying to do this by looping through the original CString and copying a character at a time into the "name cstring" until it reads a ' '. I'm having a hard time understanding why it's not stopping at the ' '. Now, if I initialize the name string with a random string that has the same amount of characters it works just fine.

Any help and tips are very welcome.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include<iostream>
#include<cstring>

using namespace std;

int main()
{
	int index = 0;
	char info_string[] = "Carl 34 Student";
	char name_string[20];
	while (info_string[index] != ' ')
	{
		name_string[index] = info_string[index];
		index++;
	}
	index++;
	
	cout << name_string;
	system("pause");
	return 0;
}
A simpler way
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
#include <iostream>
#include <sstream>
using namespace std;

int main()
{
	string testString = "Carl 34 Student";
	stringstream ss;
	ss<<testString;
	
	string name,age,title;
	string array[3] = {name,age,title};
	string temp;
	int n = 0;
	
	while(ss>>temp)
	{
		array[n] = temp;
		++n;
	}
	
	for(int i = 0; i < n; i++)
		cout<<array[i]<<endl;
	cin.ignore();
	return 0;
}
Thank you. I appreciate your reply. It's nice seeing different ways of doing things.

However, I'm still trying to figure out how these CStrings work and why my output is adding symbols after it should stop.

Now, the output on the C++ shell on this site seemed to work just fine on my code. I wonder if there's something different about my compiler that is causing the weird output or if it has something to do with the memory being used.
Just thought i should show you another method. But about your problem..
1
2
3
4
5
6
7
8
9
10
11
while (info_string[index] != ' ')
{
	name_string[index] = info_string[index];
	index++;
	name_string[index] = '\0';//append NULL to the last index.
		//makes name_string a string.(NOT JUST AN ARRAY OF CHARS)
}
//name_string[] = {'C','a','r','l'};  (ARRAY OF CHARS)
//name_string[] = {'C','a','r','l','\0'}; (STRING)
//so when the program is reading to output the string,
//it should end where it will end where it meats '\0'. 
Last edited on
Thanks! I see my mistake now.
And I wasn't being sarcastic on my previous reply. I really do appreciate seeing a different way of doing it. Probably one that is used more often.
But again, I just wanted to understand what was going on in my code.

Thanks again!

Edit PS: I'm adding your code to my handy dandy list of codes.
Last edited on
Topic archived. No new replies allowed.