0

所以,我试图让这段代码将从文件输入的每一行解析为单独的标记,然后将每一行依次添加到 tklist 数组中。然后主要只是打印出每个令牌。虽然它正在打印空白,当我进入代码时,它看起来 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;

}

就像我说的,当我调试时,它看起来像是复制问题,但我是初学者,所以我怀疑我做错了什么。

谢谢你提供的所有帮助!!

4

3 回答 3

1

尝试类似的东西

tklist[count][toklength]='\0';

strncpy(tklist[count], &cline[i-toklength], toklength);

strncpy()不一定会为您添加空终止符。strncpy 需要注意安全使用。

如果 source 比 num. 长,则不会在目标末尾隐式附加空字符。

只是对于初学者......还有其他更深层次的问题,如评论中提到的。

于 2013-05-13T21:55:55.243 回答
0

从 malloc/free 的通用等价物开始是 new/delete(堆内存分配)。

其次,您似乎混淆了字符串和 c_strings(好旧的 char*)。getline 使用字符串,您的解析函数使用 c_strings 它们不是相同的东西,并且有 .c_str() 字符串的成员函数来进行转换。

于 2013-05-13T22:28:06.857 回答
0

所以,我试图让这段代码将从文件输入的每一行解析为单独的标记,然后将每一行依次添加到 tklist 数组中。

为了

从文件输入的每一行

采用

std::ifstream ifs;
std::string s;
/**/
std::getline(ifs, s);

采用您的循环。

将 [..] 解析为单个标记

看看 std::string 如何帮助您完成该任务(或使用boost::tokenizer)。

还有这个

然后将每个 [token] 依次添加到 tklist 数组中。

几乎需要 std::list 或 std::vector 而不是普通的 C 数组,选择使用哪个容器取决于您打算如何处理找到的标记。

于 2013-05-13T22:50:38.720 回答