所以,我试图让这段代码将从文件输入的每一行解析为单独的标记,然后依次将每个标记添加到 tklist 数组。然后 main 只打印出每个标记。虽然它正在打印空白,但当我进入代码时,它看起来像 strncpy 不工作。任何想法是什么问题?我没有收到任何错误。
这是主要功能:
#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;
for (t=1; t <= numtokens; t++) {
cout << "Token "<< t << ": " << token[t-1] << "\n";
}
}
return 0;
}
这里是 parseCommandLine 函数:
int parseCommandLine(char cline[], char *tklist[]){
int i;
int length; //length of line
int count = 0; //counts number of tokens
int toklength = 0; //counts the length of each token
length = strlen(cline);
for (i=0; i < length; i++) { //go to first character of each token
if (((cline[i] != ' ' && cline[i-1]==' ') || i == 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] == '"') {
do {
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;
for (j = 0; j < count; j++) {
free( (void *)tklist[j] );
}
return count;
}
就像我说的,当我调试时它看起来像是复制问题,但我是初学者所以我怀疑我做错了什么。
感谢您提供的任何帮助!!
最佳答案
尝试类似的东西
tklist[count][toklength]='\0';
之后
strncpy(tklist[count], &cline[i-toklength], toklength);
strncpy() 不一定为您添加空终止符。 strncpy 需要小心才能安全使用。
No null-character is implicitly appended at the end of destination if source is longer than num..
只是为了初学者......还有评论中提到的其他更深层次的问题。
关于c++ - 输出错误。可能的 strncpy 问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16531600/