Problem using getline and strtok together in a program

In the program below, I intend to read each line in a file in line, line break and display single words. The problem I am facing is that now the program only displays 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<<" ";
        }

    }

}
+5
source share
3 answers

I am new to C ++, but I think an alternative approach might 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 mark each line based on the separation of spaces (so this includes more than just spaces, such as tabs and newlines).

+3
source

, . strtok() , std::string .

std::string, c_str(), const char* (.. ). strtok() char* .

strtok(), , , std::string std::vector - :

std::string s("hello, world");
std::vector<char> v(s.begin(), s.end());
v.push_back('\0');

( &v[0]) strtok().

Boost, Boost Tokenizer. .

+2

What James McNellis says is correct.

For a quick fix (though not the best) instead

string store

using

const int MAX_SIZE_LINE = 1024; //or whatever value you consider safest in your context.
char store[MAX_SIZE_LINE];
0
source

All Articles