输出错误.可能存在强度问题
Output wrong. Possible strncpy issue?
因此,我试图让这段代码解析从文件中输入的每一行为单个令牌,然后依次将每个令牌添加到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数组,选择使用哪个容器取决于你打算如何处理找到的标记。
相关文章:
- C++quit()函数中可能存在作用域问题
- 这个极客对极客的trie实现是否存在内存泄漏问题
- C++LinkedList问题.数据类型之间存在冲突?没有匹配的构造函数
- gcc和clang在表达式是否为常量求值的问题上存在分歧
- C++Builder中的OnClick事件签名存在问题
- 当我使用 C++ 中的 C# dll 来使用 Selenium 时,存在异常处理问题
- C++ 中的函数 GetCursorPos() 和 SetCursorPos() 存在一些问题
- 在 C++ 中使用逗号的 echo 命令中存在问题
- Malloc 在使用线程并行化 SSH 调用时存在问题
- 将文件复制到自定义位置,存在字符串转换问题
- 构造函数 (C++) 中的 char 指针参数存在问题
- 在 boost::variant 中类 holden 的复制构造函数存在问题
- 具有sleep_for和sleep_until功能的 gcc 可能存在的问题
- 用户定义的文本运算符(在原始模式下)存在问题
- 以下代码中存在哪些问题?
- 这种比较是否不一致(或者存在其他问题)?
- C++中的数组存在问题
- 用于检测函数是否存在的C++元函数的问题
- 以下代码存在哪些问题?
- 我的选择排序代码是否存在导致它跳过数组中的元素的问题?