c++ - 输出错误。可能的 strncpy 问题?

标签 c++ pointers malloc free strncpy

所以,我试图让这段代码将从文件输入的每一行解析为单独的标记,然后依次将每个标记添加到 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/

相关文章:

c++ - 编辑存储在字节数组中的数据

c++ - 无法从 'const std::string [3]' 转换为 'std::string'

c++ - 四舍五入正数或负数

c - (1)在函数 ‘main’ :(2) warning: format ‘%d’ expects argument of type ‘int’ , 中,但参数 2 的类型为 ‘int *’ [-Wformat]

c:释放 char* 而不破坏 char**

c++ - 在 B 树中存储键值对

c# - 根据程序内存查找新地址

c++ - 浅拷贝共享指针吗? (C++)

c - 为什么不能使用 malloc 在 C 中调整数组大小?

c - *ptr 和 **ptr 有什么区别?