c++ - How to separate one input into multiple by the spaces -


i new c++ , trying write program can sort set of names (in alphabetic order) input i'd make can input names @ once; have coded sorting , have tested multiple names fine right have push enter after every name signify new one. searched way separate input based off spaces in input found separates first 2 words/names:

    int main(){          string input;         getline(cin, input);         string temp1;         string temp2;      (int = 0; < input.length(); i++){          if (input[i] == ' ') {                 temp1.append(input.substr(0, i));                 temp2.append(input.substr(i + 1, input.length() - 1));                 break;         }     }          cout << temp1 << endl;         cout << temp2 << endl; } 

i have played around parts appear separate code , tried make them repeat every space can't work. said, i'm new c++ if please steer me in right direction or suggest better way accomplish i'm trying great.

thanks,

-eric

---edit---

example input:

william charlie sarah peter matt john

example output:

charlie john matt peter sarah william

(as said, have program name ordering, need know how input names @ once , have program assign first temp1, second temp2, third temp3, etc.)

#include <iostream> #include <sstream> #include <vector> #include <algorithm> using namespace std;  vector<string> separate_string(const string& input) {     istringstream input_stream(input);     string buffer;     vector<string> separated;      while (input_stream >> buffer)     {         separated.push_back(buffer);     }      return separated; }  int main() {     string test_string = "william charlie sarah peter matt john";     auto names = separate_string(test_string);     sort(begin(names),end(names));     (const auto& s : names)         cout << s << endl; } 

explanation:

the object input_stream of type std::istringstream takes string on contruction. then, can use cin. using extraction operator >>, string separated space characters.

the while-loop stops when reaches end of input string.

the separated strings stored in vector string.

the main test program. may write own complete mission.


Comments

Popular posts from this blog

c# - HttpResponseMessage System.InvalidOperationException -

sql - Postgresql error: "failed to find conversion function from unknown to text" -