gpt4 book ai didi

c++ - 如何修复strtok编译器错误?

转载 作者:行者123 更新时间:2023-11-30 17:02:48 24 4
gpt4 key购买 nike

嗨,所以我正在编写这段代码来查看一个文本文件,并将它找到的每个单词放入一个 C 字符串数组中。我能够编写代码,但当实际文本文件中存在错误时,我会遇到问题。例如,如果句子中有两个空格(例如“汽车走得快”),我的程序就会崩溃,它会停在汽车处。看看我的代码,我相信这是因为 strtok。我认为要解决这个问题,我需要让 strtok 制作下一个值的 token ,但我不知道该怎么做

我的代码

#include <iostream>
#include <fstream>
#include <string.h>
#include <stdlib.h>
using namespace std;

int main() {
ifstream file;
file.open("text.txt");
string line;

char * wordList[10000];
int x=0;

while (getline(file,line)){

// initialize a sentence
char *sentence = (char*) malloc(sizeof(char)*line.length());
strcpy(sentence,line.c_str());

// intialize a pointer
char* word;

// this gives us a pointer to the first instance of a space, comma, etc.,
// that is, the characters in "sentence" will be read into "word"
// until it reaches one of the token characters (space, comma, etc.)
word = strtok(sentence, " ,!;:.?");

// now we can utilize a while loop, so every time the sentence comes to a new
// token character, it stops, and "word" will equal the characters from the last
// token character to the new character, giving you each word in the sentence

while (NULL != word){
wordList[x]=word;
printf("%s\n", wordList[x]);
x++;
word = strtok(NULL," ,!;:.?");
}
}
printf("done");
return 0;
}

我知道有些代码是用 c++ 编写的,有些是用 c 编写的,但我试图用 c 来完成大部分代码

最佳答案

问题可能是您没有为空终止字符串分配足够的空间。

  char *sentence = (char*) malloc(sizeof(char)*line.length());
strcpy(sentence,line.c_str());

如果需要捕获“abc”,则需要 3 个字符元素和另一个终止空字符元素,即总共 4 个字符。

malloc 的参数值需要增加 1。

  char *sentence = (char*) malloc(line.length()+1);
strcpy(sentence,line.c_str());

不清楚为什么在 C++ 程序中使用 malloc。我建议使用new

  char *sentence = new char[line.length()+1];
strcpy(sentence,line.c_str());

关于c++ - 如何修复strtok编译器错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36416225/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com