Split String

Hello C++ peoples,

I am brand new at C++. Three months and I think I really like it. I am not an member of any C++ forum until now. I search google for answers and most of the time I end-up here reading code and I must say this forum has silently help me solved a few problems that I could find no where else ... until "NOW" :)


I'm trying to put together a function that will do this:

Please type your first and last name:
Sam Harris
Your First Name is:
Sam
Your Last Name is:
Harris


This is about the only code I found while googling that even came close. Could someone fix this to do what I'm after. I learn better by example. I read and play with working code until I understand what it does.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <sstream>
#include <string>
using namespace std;

int main()
{
    string s("Sam Harris");
    istringstream iss(s);

        string sub;
        iss >> sub;
        cout << "First Name: " << sub << endl;

        iss >> sub;
cout << "Last Name: " << sub << endl;
    return 0;
}


This is the program I am trying to build stuff in. Mainly as a collection of build-in example of special code that can be refer to. Size is more important than speed for now.

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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <iostream> 
#include <sstream>
#include <string>
using namespace std;

string EXTRA_COPY;

string s("Sam Harris");
istringstream iss(s);

class DataRecoder
{
public:
   void setName( string name )
   {
   _data = name;//  store_name_in_object
   }
// .......................................................................
   string get_Entered_Data()
   {
 EXTRA_COPY = _data;  
   
   return _data;
   }
// .......................................................................

   void displayMessage()
   {
      cout << "First Name: \n" << get_Entered_Data()
         << endl;

        string sub;
        iss >> sub;
        cout << "First Name: " << sub << endl;

        iss >> sub;
cout << "Last Name: " << sub << endl;
   }
// .......................................................................
private:
   string _data;
};
// ......
// ......
// ......

int main()
{
string firstName;
DataRecoder myDataRecoder;
//istringstream iss(string);

cout << "\nPlease enter your first and last name: " << endl;
getline( cin, firstName );
myDataRecoder.setName( firstName );

cout << endl;
myDataRecoder.displayMessage();

}


I like the first little code but I'll be happy with anything that works. It must be a very difficult thing to do because there are tons of split string and other functions on the INTERNET but not one of them do what I'm after no matter what keyword I tried to search with.

Thanks in advance


Just a few good link to keep track of and I found this one today :)

http://www.cplusplus.com/forum/beginner/545/
Sooner or later, you will come across boost http://www.boost.org/ - if you choose to use it, here is a viable option:
1
2
3
4
5
6
7
8
9
10
11
#include <string>
#include <vector>

#include <boost/algorithm/string/split.hpp>

using namespace std;

string s("Sam Harris");
vector<string> strs;

boost::split( strs, s, boost::is_any_of( " " ));  // did it without using namespace boost; so you can see the scope 

There are many options for doing this - including rolling your own (if you are so inclined).
Last edited on
Here's a simple one I've made in the past.

1
2
3
4
5
6
7
8
9
namespace custom{
  void split(string &s1, string &s2, char delim){
    size_t i;

    i=s1.find_first_of(delim);
    s2.append(s1, i+1, s1.size());
    s1.erase(i, s1.size());
  }
}
Sooner or later, you will come across boost http://www.boost.org/ - if you choose to use it, here is a viable option:

Dang kfmfe04, that code looks soooo good but could you post an example with-out the use of boost.

Thanks meesa, but it be months before we even see code like that. I will be looking into all of this the rest of the night. Boost and namespace custom going to be a good head-start.

I didn't want to mention it but actually this is my first programming class ever, C/C++, and I don't want to use what the instructor may not be using. I been hacking with this for over 24 hours with no luck, and after many days of reading, it's not even in the textbook what-so-ever or Chapter-3. Could be a typo in the assignment or the instructor would simply like to know how-to himself. Nine out of ten his true field is law. heehee

I use to write some great assembler for Windows in masm and fasm and for me, I assure you, moving to C++ is as difficult as moving from c++ to assembler. I need to see the code. I will understand it as I tamper with it just as I did with asm. With-in a few months I'll be benchmarking everything I see and write.

I found this code below to be interesting but my Microsoft Visual Studio 8.0 can't find this mscorlib.dll. See what I mean. Even the instructor might not have it. Any ideas about this. He grade all project by "Start without debugging" Also do you know anything about this mscorlib.dll

Thanks for the reply

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#using <mscorlib.dll>

using namespace System;
using namespace System::Collections;

int main()
{

   String* delimStr = S" ,.:";
   Char delimiter[] = delimStr->ToCharArray();
   String* words = S"one two,three:four.";
   String* split[] = 0;

   Console::WriteLine(S"The delimiters are -{0}-", delimStr);
   for (int x = 1; x <= 5; x++) {
      split = words->Split(delimiter, x);
      Console::WriteLine(S"\ncount = {0, 2} ..............", __box(x));
      IEnumerator* myEnum = split->GetEnumerator();
      while (myEnum->MoveNext()) {
         String* s = __try_cast<String*>(myEnum->Current);
         Console::WriteLine(S"-{0}-", s);
      }
   }
}

Don't worry about looking into namespace custom, as you won't find anything. You'll understand that bit when you get to it, and it'll work perfectly find with that taken out (Don't forget the closing bracket of it as well)


I didn't want to mention it but actually this is my first programming class ever, C/C++, and I don't want to use what the instructor may not be using.

Do yourself a favor and meantion those things, or you'll get some more advanced answers as above.

Here is a way to do is with pure C++ that you should be familiar with.

1
2
3
4
5
6
7
8
9
10
11
12

void splitMe(string &s1, string &s2, char delim){
  string temp(s1.size());
  int i;
  for(i=0; s1.at(i)!=delim; i++){
    temp.at(i)=s1.at(i);
  }
  for(; i<s1.size(); i++){
    s2.at(i)=s1.at(i);
  }
  s1=temp;
}
I forgot to mentions that this program is based on user input at the keyboard. So I think getLine has to be used:

My main problem is replacing string s("Sam Harris"); with a getLine function. I just don't know how-to.

This is an most unusual way I seen. Notice how user type full name on one line, but the code must make two lines out of it plus an header (Your First Name is:)

Please type your first and last name:
Sam Harris
Your First Name is:
Sam
Your Last Name is:
Harris


Now I going to study what you guys have shown me. The for-each and other looping code begins next week in Chapter-4 . This was too early of an assignment. Ohh well, it's fun trying FUN and I join the best C++ Forum to boot! ...
Thanks again







Tip 1: Meantion everything in your first post, or you'll get on a lot of people's nerves.
Tip 2: Have you tried googling "C++ string getline"?

http://www.cplusplus.com/reference/string/getline/

Tip 1: Meantion everything in your first post, or you'll get on a lot of people's nerves.


It's difficult to say everything in a first post but if you look again you will realized that I asked a very complete question. Once again, this is the point of my first post:

1) The code below works for one type of use but could someone change it to show user keyboard input to replace the [embedded full name TYPE] in the string shown at line-12 so that the user can do something "exactly" like this:

Please type your first and last name:
John Doe
Your First Name is:
John
Your Last Name is:
Doe


You guys are the experts. You should have known I needed a getLine function off the top, but no one post an example with it, only split-string examples that works near the same way as the code I posted, anyway. I did not complain.

SAME 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 <sstream>
#include <string>
using namespace std;

int main()
{

// useless. We need user keyboard input.  Not embeded name
// in Standard C++ which is the norm.
 
string s("John Doe");
istringstream iss(s);

        string sub;
        iss >> sub;
        cout << "First Name: " << sub << endl;

        iss >> sub;
cout << "Last Name: " << sub << endl;
    return 0;
}

Last edited on
I don't see anywhere in your original post a request for the user to input (Sorry if I'm being blind), nonetheless, use the link above to use getline to input into a string.
Last edited on
It's funny, It's true, I never been to a place where anyone knows what I am taking about for a long time, no matter how hard I try to explain and I know they were sincere. But I think this is one in my favor .. hee hee

So I think getLine has to be used: My main problem is replacing string s("Sam Harris"); with a getLine function. I just don't know how-to.


That was the question but Thanks for the link. Now I know a lot more about getLine. I used getLine for a few weeks but never under a situation like this.


Everybody knows how to:

Please type your first and last name:
John Doe
Thankyou

But it seem no one knows how to:

Please type your first and last name:
John Doe
Your First Name is:
John
Your Last Name is:
Doe


I'm sure this code is only a hair away from working:

#include <iostream>
#include <sstream>
#include <string>
using namespace std;

int main()
{
string s("Sam Harris");
istringstream iss(s);

string sub;
iss >> sub;
cout << "First Name: " << sub << endl;

iss >> sub;
cout << "Last Name: " << sub << endl;

string str;
cout << "Please enter full name: ";
getline (cin,str);
cout << "Thank you, " << str << ".\n";

return 0;
}

I'm a bit confused on what you're doing, your psudeo output doesn't match that which you code writes.

If you'll use getline like you have in the above code, and then split it with the above code I posted (Or similiar) then it should work.

BTW, wrap your code in [code] tags.
You can try extrapolating from this:
1
2
std::string name("First Last");
std::cout<<name.substr(0, name.find(" "));
Topic archived. No new replies allowed.