0

Is it possible to get each words of a line extracted with getline?

for example, with this example as a "test.txt" file:

18407111  2018-07-05 00:04:02  MHAM  EIDW  42  S1REB  RYR5GW  3726  JNEIE  837B  Datum  RYR  IFR  Undefined  1  1  2018-07-05  00:15:38  2018-07-05  00:22:56  111  extended
0.0  113416.9  479798.5  -0.2  3.6  0.0

I can get the first line in a loop with getline(file,line) but from this line, i want to browse each "words" that are in it starting with "18407111".

I tried something but i only managed to get the first word.

#include <iostream>
#include <fstream>

main() {
    int info[100][6] = {0};
    int  i =0, j;
    std::ifstream file {"test.txt"};
    std::string line;
    std::string word;
    while (getline(file,line))
    {
        word = line.substr(0, line.find(" "));
        std::cout << word << "\n";
        std::stoi(word)>> info[i][0];
        i++;
        return 0;
           }
    }

I need those data separate in order to work with it like:

18407111
2018
07
05
00
04
02
MHAM
etc...
Ken White
  • 123,280
  • 14
  • 225
  • 444
Random
  • 41
  • 6
  • Please don't tag spam. Your question is not about any of those specific C++ versions, but about generic C++. I've removed the excessive, not applicable tags. – Ken White Jul 16 '21 at 00:27
  • 1
    Why use `getline` in the first place? Why not just `while (file >> word)`? – KamilCuk Jul 16 '21 at 00:29
  • @KamilCuk because when i use file >> word i don't manage to get all the data afterwards "0.0 113416.9 479798.5 -0.2 3.6 0.0" to store them in an array because it either skips the first or the last value with the loop – Random Jul 16 '21 at 06:38

1 Answers1

4

Just use stringstream and read the word.

while (getline(file,line))  {
   std::istringstream ss(line);
   std::string word;
   while (ss >> word) {
         std::cout << "This is the word: " << word << "\n";
   }
}

but you can just while (file >> word) straight anyway.

KamilCuk
  • 120,984
  • 8
  • 59
  • 111
  • 1
    Consider using `std::istringstream` instead of `std::stringstream` – Remy Lebeau Jul 16 '21 at 01:14
  • [What's the difference between istringstream, ostringstream and stringstream? / Why not use stringstream in every case?](https://stackoverflow.com/q/3292107/3422102) -- I was curious too. Crux, `i/o...` provides clear expression of intent, and `stringstream` itself would be larger and slightly less efficient (emphasis on *slightly* - though no time or memory comparisons are provided in the linked question) – David C. Rankin Jul 16 '21 at 02:14
  • Thanks for your answers. Shouldn't it be `while (ss>>line)` instead? I can't use file>>word because when i store data it can skips words – Random Jul 16 '21 at 06:59
  • @Random yes, it should be! – KamilCuk Jul 16 '21 at 07:01