Click here to Skip to main content
14,639,066 members
Rate this:
Please Sign up or sign in to vote.
See more:
I need to read input from stdin and store the values into a array, such that each word in a line is stored as an array of strings.

Example:
Stdin:
Hello. My name is A.
I am from B.

Output:
{
{"Hello.","My","name","is","A."},
{"I","am","from","B."}
}

Appreciate any help.

What I have tried:

I have tried putting entire line into a single string, but I am not able to break it out.

int num_of_lines = 5;
string str_arr[num_of_lines];
for(int i=0;i<num_of_lines;i++){
getline(cin="">>ws,str_arr[i])
}

with this, I get the output as
{"Hello. My name is A.",
"I am from B."}
Posted
Updated 11-Nov-19 22:41pm

1 solution

Rate this:
Please Sign up or sign in to vote.

Solution 2

I would use std::vector and std::istringstream. The program
#include <iostream>
#include <vector>
#include <sstream>
using namespace std;

int main()
{
  const std::string input = "Hello. My name is A.\nI am from B.\n";

  vector <vector < string > > vline;

  while ( true )
  {
    string line;
    getline(cin, line);
    if ( ! cin ) break;
    vector <string> vword;
    istringstream iss ( line );
    while ( true )
    {
      string word;
      iss >> word;
      if ( ! iss ) break;
      vword.push_back( word );
    }
    vline.push_back( vword );
  }

  cout << "{\n";
  for (const auto & vw : vline)
  {
    cout << "{";
    for ( const auto & w  : vw )
    {
      cout << "\"" << w << "\", ";
    }
    cout << "},\n";

  }
  cout << "}\n";
}
fed with
Hello. My name is A.
I am from B.
produces
{
{"Hello.", "My", "name", "is", "A.", },
{"I", "am", "from", "B.", },
}

Such an output, while not exactly the one requested, it is an acceptable ( :-D ) imitation.
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100