Click here to Skip to main content
15,886,519 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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

I would use std::vector and std::istringstream. The program
C++
#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.
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900