hans
hans

Reputation: 147

How can I take a string input like this?

If I have a string containing unknown number of words, and I have to scan it in multiple strings in C++. How can I do it?

For eg: 
"I am a boy". I want, each of these individual words to be in a string. 
"My name is John Lui". Each of these as well. 

One way that I could think of was to use, getline in c++ and then parse through the entire string until a character is found and store in seperate strings. I want to know is there a better method? Thanks!

Also, I want to know, that when using a delimiter in getline command, getline basically scans the input strings till the point delimiter is not found and puts that part of a string into a new string. However, I want to know, if the delimiter is not present at all, then what happens? Does it throw an exception or it takes input the whole string till the newline character? Thanks!

Upvotes: 0

Views: 100

Answers (1)

Sakib Ahammed
Sakib Ahammed

Reputation: 2480

However you could use std::getline

Which uses a string instead of a char array. It's easier to use string since they know their sizes, they auto grow etc. and you don't have to worry about the null terminating character and so on. Also it is possible to convert a char array to a string by using the appropriate string contructor.

You can do it by stringstream:

// stringstream::str
#include <string>       // std::string
#include <iostream>     // std::cout
#include <sstream>      // std::stringstream, std::stringbuf

using namespace std;
int main ()
{
    std::string str;
    getline( std::cin, str );
    std::stringstream ss;
    ss<<str;
    std::string s;
    while(ss>>s)
    {
        std::cout << s << '\n';
    }
    return 0;
}

Input: I am a boy

Output:

I
am
a
boy

If you think that, you want each word to store in a vector, you can do it like:

// stringstream::str
#include <string>       // std::string
#include <iostream>     // std::cout
#include <sstream>      // std::stringstream, std::stringbuf
#include <vector>
using namespace std;
int main ()
{
    vector <string> V;
    V.clear();
    std::string str;
    getline( std::cin, str );
    std::stringstream ss;
    ss<<str;
    std::string s,s1;
    while(ss>>s)
    {
        V.push_back(s);
    }
    return 0;
}

Upvotes: 2

Related Questions