I’m trying to read information from a file and process that information in a certain way. I need to make an array of all the words on the very left hand side of the file that don’t have white space in front of them. I keep however getting really odd output when I try to display the contents of that char array.
Here is the sample input:
# Sample Input
LA 1,3
LA 2,1
TOP NOP
ADDR 3,1
ST 3, VAL
CMPR 3,4
JNE TOP
P_INT 1,VAL
P_REGS
HALT
VAL INT 0
TAN LA 2,1
So for instance when I run my program, my output should be:
TOP
VAL
TAN
Instead I’m getting:
a
aTOP
aVAL
aTAN
a
a
I’m not sure why this is happening. Any minor changes I make don’t actually help, they just change what’s in front of my expected output. Sometimes it’s ASCII value 0 or 20 characters. Hopefully someone can help me fix this because it’s driving me crazy.
Here’s my code:
#include <string>
#include <iostream>
#include <cstdlib>
#include <string.h>
#include <fstream>
#include <stdio.h>
using namespace std;
int main(int argc, char *argv[])
{
// If no extra file is provided then exit the program with error message
if (argc <= 1)
{
cout << "Correct Usage: " << argv[0] << " <Filename>" << endl;
exit (1);
}
// Array to hold the registers and initialize them all to zero
int registers [] = {0,0,0,0,0,0,0,0};
string memory [16000];
string symTbl [1000][1000];
char line[100];
char label [9];
char opcode[9];
char arg1[256];
char arg2[256];
char* pch;
// Open the file that was input on the command line
ifstream myFile;
myFile.open(argv[1]);
if (!myFile.is_open())
{
cerr << "Cannot open the file." << endl;
}
int counter = 0;
int i = 0;
while (myFile.good())
{
myFile.getline(line, 100, '\n');
// If the line begins with a #, then just get the next line
if (line[0] == '#')
{
continue;
}
// If there is a label, then this code will run
if ( line[0] != '\t' && line[0]!=' ')
{
if( pch = strtok(line-1," \t"));
{
strcpy(label,pch);
cout << label << endl;
}
if (pch = strtok(NULL, " \t"))
{
strcpy(opcode,pch);
}
if (pch = strtok(NULL, " \t,"))
{
strcpy(arg1,pch);
}
if (pch = strtok(NULL, ","))
{
strcpy(arg2, pch);
}
}
}
return 0;
}
You are passing
line-1tostrtok, which will cause it to return a pointer to the character before the start of the string; accessingline[-1]will produce undefined behaviour.strtoktakes a pointer to the start of a string.You’ve also got a
;at the end of yourif( pch = strtok(line-1," \t"))statement, which nullifies theiftest and causes the block to run even ifpchisNULL.