I got line which looks like: name1 - name2 (example: Josh - Marc) I need to take those 2 names as 2 different strings. I don't know how I could avoid this "-" while reading that line.. Any ideas? Thanks in advance,
Asked
Active
Viewed 59 times
-4
-
2Call me old fashioned but I try to write some code to do this. – Ed Heal Jan 30 '16 at 12:55
-
Possible duplicate of [Split a string in C++?](http://stackoverflow.com/questions/236129/split-a-string-in-c) – Pustovalov Dmitry Jan 30 '16 at 12:55
-
Just split the string into tokens, then get rid of any '-' tokens ... [boost tokenizer](http://theboostcpplibraries.com/boost.tokenizer) is a simple solution. – RobClucas Jan 30 '16 at 13:00
2 Answers
0
If the String pattern is known then you can parse it ex:
std::string s = "Josh - Marc";
std::string delimiter = "-";
std::string token = s.substr(0, s.find(delimiter));

Raju
- 2,902
- 8
- 34
- 57
-
Yeah I know this, but how to read it as input? If input is "Josh - Marc" (1 line)? I cannot just use cin, because there are spaces.. – Artegor Jan 30 '16 at 13:01
-
Maybe you should mention in the question that you don't know how to get the input in the way you want it, if that's your problem. – RobClucas Jan 30 '16 at 13:02
-
@Artegor you can read line with following `std::getline (std::cin,name);` . i advise you to use [Google](http://www.google.com) before [StackOverflow](http://stackoverflow.com/) – tchelidze Jan 30 '16 at 13:04
0
Here is demo code.You can do it this way also,
#include <stdio.h> #include <iostream> using namespace std; int main() { char string[20], name1[20], name2[20]; gets(string); int j = 0, k = 0; int i = 0; while(string[i] != '-') { name1[i] = string[i]; i++; } while(string[i] != '\0') name2[j++] = string[++i]; cout<<name1<<" "<<name2; }

Sagar Patel
- 864
- 1
- 11
- 22