输出错误.可能存在强度问题

Output wrong. Possible strncpy issue?

本文关键字:问题 存在 错误 输出      更新时间:2023-10-16

因此,我试图让这段代码解析从文件中输入的每一行为单个令牌,然后依次将每个令牌添加到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.nn";
        return 0;
    }
    while (!inFile.eof())
    {
    inFile.getline(line, 255);
    line[strlen(line)+1] = '';
    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] != '') && (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]='';

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

strncpy()不一定为您添加空终止符。Strncpy需要谨慎使用。

没有空字符隐式地附加在目标if的末尾

首先…

首先,malloc/free的通用等价物是new/delete(堆内存分配)。

第二,你似乎混淆了字符串和c_strings(好的旧char*)。Getline使用字符串,你的解析函数使用c_string,它们不是一样的东西,有。c_str()一个string的成员函数来做转换。

所以,我试图让这段代码解析从文件到单独的令牌,然后依次添加到tklist数组。

从文件

输入的每一行

使用

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

采用到你的循环。

解析[. .]变成单独的令牌

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

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

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