-1

I have to make a code that read a line strings from user and divides this string when there is a space, store and then do some operations with this input.

For example the input can be like That :

"set 11643133 name Alex Jon"

all this it have to be input in a one line, and I have to divide it for set a name "Alex Jon" to the student's ID "11643136"

I really have to hand the project in nearest time, I just want to ask if there is a simple way or some standard commands maybe can it helps me at that ?

*I use getstr() and string.substr()

  • Use `std::getline` to read lines of text. Then, use the answers from https://stackoverflow.com/questions/236129/the-most-elegant-way-to-iterate-the-words-of-a-string to split a line into tokens. Process the tokens using whatever logic makes sense. – R Sahu Oct 24 '17 at 22:08
  • This question already got an answer here https://stackoverflow.com/questions/14265581/parse-split-a-string-in-c-using-string-delimiter-standard-c – Brighter side Oct 24 '17 at 22:08
  • I think this is the 5th homework assignment I see tonight XD.... Nevertheless; be aware when splitting on a space, most systems use `"` to combine "separated" arguments. (you might need it with "Alex Jon") – Stefan Oct 24 '17 at 22:10
  • `strtok` is a simple C function for tokenising strings. Code would look something like this (can't post answer bc closed). https://gist.github.com/Robadob/e7a6d96afebc57fbafd7f0ec904a1a84 – Robadob Oct 24 '17 at 22:15

1 Answers1

0

This problem boils down to splitting the string by spaces. You can use the istringstream for splitting. Then apply whatever logic you have on these tokens.

string s;
getline(std::cin,s);
istringstream iss(s);
vector<string> tokens;
string tmp;

//read tokens
while(iss>>tmp) {
    tokens.push_back(tmp)
}

Now tokens consisits of all your words given by the user as an input.

97amarnathk
  • 704
  • 1
  • 8
  • 28