c++ - Output wrong. Possible strncpy issue? -
so, i'm trying code parse each line inputted file individual tokens, add each 1 in turn tklist array. main prints out each token. it's printing blanks though, , when step code looks strncpy isn't working. ideas issue is? no errors.
here's main function:
#include <iostream> #include <fstream> using namespace std; #include "definitions.h" #include "system_utilities.h" int main() { ifstream infile; char line[max_cmd_line_length]; char* token[max_tokens_on_a_line]; int numtokens; system("pwd"); infile.open("p4input.txt", ios::in); if(infile.fail()) { cout << "could not open input file. program terminating.\n\n"; return 0; } while (!infile.eof()) { infile.getline(line, 255); line[strlen(line)+1] = '\0'; numtokens = parsecommandline(line, token); int t; (t=1; t <= numtokens; t++) { cout << "token "<< t << ": " << token[t-1] << "\n"; } } return 0; }
and here's parsecommandline function:
int parsecommandline(char cline[], char *tklist[]){ int i; int length; //length of line int count = 0; //counts number of tokens int toklength = 0; //counts length of each token length = strlen(cline); (i=0; < length; i++) { //go first character of each token if (((cline[i] != ' ' && cline[i-1]==' ') || == 0)&& cline[i]!= '"') { while ((cline[i]!=' ')&& (cline[i] != '\0') && (cline[i] != '\r')){ toklength++; i++; } //--------------- tklist[count] = (char *) malloc( toklength +1); strncpy(tklist[count], &cline[i-toklength], toklength); //-------------- count ++; toklength = 0; } if (cline[i] == '"') { { toklength++; i++; if (cline[i] == ' ') { toklength--; } } while (cline[i]!='"'); //-------------- tklist[count] = (char *) malloc( toklength +1); strncpy(tklist[count], &cline[i-toklength], toklength); //-------------- count ++; toklength = 0; } } int j; (j = 0; j < count; j++) { free( (void *)tklist[j] ); } return count; }
like said, when debug looks problem copying, i'm beginner suspect i'm doing wrong.
thanks can give!!
try like
tklist[count][toklength]='\0';
after
strncpy(tklist[count], &cline[i-toklength], toklength);
strncpy() not necessarily add null terminator you. strncpy needs care use safely.
no null-character implicitly appended @ end of destination if source longer num..
just starters... there other deeper issues mentioned in comments.
Comments
Post a Comment