I am writing a program right now that tokenizes multiple strings from a text file.
I have a while
loop that continues to run until the end of the file. And nested in that loop, I have another while
loop using strtok()
to tokenize strings.
But, in my nested while
loop with strtok()
, I test with an if
statement to see if I get NULL
at the end of a string, but I never receive the NULL
value. After the nested loop, it seems to break out of both loops, and also skips code outside of the main while
loop, and ends my program with return 0;
.
#include<iostream>
#include<fstream>
#include<string.h>
#include<iomanip>
using namespace std;
int main(int argc, char* argv[])
{
//variable declarations
ifstream inputfile;
ofstream outputfile;
char line[100];
char* ptr;
//check how many arguments in command line
cout << "argc: " << argc << endl << endl;
//check if there is input and output command line argument
if (argc < 3)
{
cout << "missing input and output files";
}
cout << argv[1] << endl;
cout << argv[2] << endl << endl;
//cout <<"Null: " << NULL << endl;
//opens input file from command line argument
inputfile.open(argv[1]);
//opens output file from command line argument
outputfile.open(argv[2]);
//check if input file is open
if (!inputfile)
{
cout << "file not open"<< endl;
}
//check for input
while (!inputfile.eof())
{
//inputfile = input, getline, line = output, 100 = delimiter
//grabs the line.
inputfile.getline(line, 100);
//check for line
cout << line << endl;
//grabs first word
ptr = strtok(line, " ");
cout << ptr << endl;
//loops until null
while(ptr!=NULL)
{
//grabs other words until end of line
ptr = strtok(NULL, " ");
cout << ptr << endl;
if (ptr==NULL)
{
cout << "hit NULL" << endl;
}
}
cout << "afterloop" << endl;
}
cout << "end";
return 0;
}