Search code examples
c++stringtokenizestrtok

Problem with using getline and strtok together in a program


In the below program , I intend to read each line in a file into a string , break down the string and display the individual words.The problem I am facing is , the program now outputs only the first line in the file. I do not understand why this is happening ?

#include<iostream>
#include<string>
#include<fstream>
#include<cstdio>
using namespace std;

int main()
{
    ifstream InputFile("hello.txt") ;
    string store ;
    char * token;

    while(getline(InputFile,store))
    {
        cout<<as<<endl;
        token = strtok(&store[0]," ");
        cout<<token;
        while(token!=NULL)
        {
        token = strtok(NULL," ");
        cout<<token<<" ";
        }

    }

}

Solution

  • I'm new to C++, but I think an alternative approach could be:

    while(getline(InputFile, store))
    {
        stringstream line(store); // include <sstream>
        string token;        
    
        while (line >> token)
        {
            cout << "Token: " << token << endl;
        }
    }
    

    This will parse your file line-by-line and tokenise each line based on whitespace separation (so this includes more than just spaces, such as tabs, and new lines).