2
  #include<sstream>
  #include<iostream>
  using namespace std;

  int main(){
     string line = "test one two three. \n another one \n";
     string arr[8];
     cout<<line;
     int i = 0;
     stringstream ssin(line);
     while (ssin.good() && i < 8){
         ssin >> arr[i];
         ++i;
     }
     for(i = 0; i < 8; i++){
        cout << arr[i];
     } 
  return 0; 
  }

//Now i want to print that elements that just come before the newline ("\n") in the string.

3 Answers3

0

Your ssin >> arr[i] skips whitespace, losing all knowledge of which arr entries were followed by newlines.

Instead, you can divide input into lines first, then words, while tracking the newlines:

std::vector<size_t> newline_after_word_index;
std::vector<std::string> words;
while (getline(ssin, line))
{
    std::istringstream line_ss(line);
    std::string word;
    while (line_ss >> word)
        words.push_back(word);
    newline_after_word_index.push_back(words.size());
}

You can then use indices from newline_after_word_index to print out the words[] entry beforehand....

Tony Delroy
  • 102,968
  • 15
  • 177
  • 252
  • actually i have no idea of vector can you implement it in my program. If possible. Thank you – Dinesh Kumar Apr 15 '16 at 05:44
  • 1
    @DineshKumar All you need to do to use `std::vector` in your program is `#include ` at the top. A `std::vector` is much like the array you used, but it can size itself - just `push_back()` new items to the end and it'll get more memory if it needs it. You can still use `words[i]` to access the elements just like your array. (You should get a good introductory C++ book). – Tony Delroy Apr 15 '16 at 06:18
0

Don't think of "test one two three. \n another one \n" as one line of text. It is not. It is two lines of text.

You need to change your strategy of reading a little bit.

int main()
{
   string input = "test one two three. \n another one \n";
   string arr[8];
   int i = 0;

   stringstream ssin_1(input);
   string line;

   // Read only the tokens from the first line.
   if ( std::getline(ssin_1, line) )
   {
      stringstream ssin_2(line);
      while ( ssin_2 >> arr[i] && i < 8)
      {
         ++i;
      }
   }

   // Don't print all the elements of arr
   // Print only what has been read.
   for(int j = 0; j < i; j++){
      cout << arr[j] << " ";
   } 

   return 0; 
}
R Sahu
  • 204,454
  • 14
  • 159
  • 270
0

http://www.cplusplus.com/reference/string/string/find/

#include<sstream>
#include<iostream>
using namespace std;
int main(){
    string line = "test one two three. \n another one \n";
    size_t found = line.find("\n");
    for (int i=0; i<=found; i++){
      cout << line[i];
    }
return 0; }
BusyTraveller
  • 183
  • 3
  • 14