First of all, the line
if (argc = 2)
is probably not doing what you intend. You should probably write this instead:
if (argc == 2)
The function std::istream::getline
requires as a first parameter a char *
, which is the address of a memory buffer to write to. However, you are passing it the 2D array words
, which does not make sense.
You could theoretically pass it words[0]
, which has space for 16
characters. Passing words[0]
will decay to &words[0][0]
, which is of the required type char *
. However, the size of 16
characters will probably not be sufficient. Also, it does not make sense to write the whole line into words
, as this 2D array seems to be intended to store the result of strtok
.
Therefore, I recommend that you introduce an additional array that is supposed to store the entire line:
char line[200];
(...)
while( inputfile.getline( line, sizeof line ) )
Also, the line
token = strtok(words[100][16], " ");
does not make sense, as you are accessing the array words
out of bounds. Also, it does not make sense to pass a 2D array to std::strtok
, either.
Another issue is that you should call std::strtok
several times, once for every token. The first parameter of std::strtok
should only be non-NULL
on the first invocation. It should be NULL
on all subsequent calls, unless you want to start tokenizing a different string.
After copying all tokens to words
, you can then print them in a loop:
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
int main(int argc, char **argv)
{
char line[200];
char words[100][16];
int counter = 0;
ifstream inputfile;
inputfile.open(argv[1]);
while( inputfile.getline( line, sizeof line) )
{
char *token;
token = strtok( line, " ");
while ( token != nullptr )
{
strcpy( words[counter++], token );
token = strtok( nullptr, " " );
}
}
//print all found tokens
for ( int i = 0; i < counter; i++ )
{
cout << words[i] << '\n';
}
}
For the input
This is the first line.
This is the second line.
the program has the following output:
This
is
the
first
line.
This
is
the
second
line.
As you can see, the strings were correctly tokenized.
However, note that you will be writing to the array words
out of bounds if
- any of the tokens has a size larger than 16 characters, or
- the total number of tokens is higher than 100.
To prevent this from happening, you could add additional checks and abort the program if such a condition is detected. An alternative would be to use a std::vector
of std::string
instead of a fixed-size array of C-style strings. That solution would be more flexible and would not have the problems mentioned above.