gpt4 book ai didi

C++ strtok问题

转载 作者:行者123 更新时间:2023-11-30 00:42:01 27 4
gpt4 key购买 nike

我正在尝试创建一个单词==>卓尔 map ,就像 polindrom ...问题出在“strtok”的最后一层......首先我拆分它,然后在后续调用中执行 strtok(NULL,"");它工作正常。问题是当我添加第二个字符串“poly_buffer”时......似乎它适用于它......

#include "stdafx.h"
#include <iostream>
#include <cstdio>
#include <string>
#include <map>
#include <string>
using namespace std;

void poly(char *buffer)
{
char temp;
for (int i=0; i<=strlen(buffer); i++)
{
int word_start = i, word_stop = i;

while (buffer[i] != 32 && buffer[i] != '\0') { i++; word_stop++; }
word_stop--;

//swap chars until the middle of word
while (word_stop >= word_start)
{
//swap the chars
temp = buffer[word_stop];
buffer[word_stop] = buffer[word_start];
buffer[word_start] = temp;
word_stop--;
word_start++;
}
word_start = i;

}
}


void main()
{
FILE *fp;
char *buffer;
char *poly_buffer;
long file_size;
map<string,string> map_poly;

fp = fopen("input.txt", "r");

if (fp == NULL) { fputs("File Error",stderr); exit(1); }

//get file size
fseek(fp,1,SEEK_END);
file_size = ftell(fp);
rewind(fp);

//allocate memory
buffer = new char[file_size+1];
poly_buffer = new char[file_size+1];

//get file content into buffer
fread(buffer,1, file_size,fp);
strcpy(poly_buffer,buffer);

buffer[file_size] = '\0';
poly_buffer[file_size] = '\0';

poly(buffer);

buffer = strtok(buffer," ");
poly_buffer = strtok(poly_buffer," ");

while (buffer != NULL)
{
map_poly[buffer] = poly_buffer;
printf("%s ==> %s\n", buffer, poly_buffer);
buffer = strtok(NULL," ");
poly_buffer = strtok(NULL," ");
}

fclose(fp);
while(1);
}

我做错了什么?

最佳答案

两个 strtok 调用

buffer = strtok(buffer, " ");
poly_buffer = strtok(poly_buffer," ");

相互干扰,你需要一个一个地处理它们——你不能同时做它们,因为它们在运行时库中共享静态内存。即首先执行 strtok(buffer,"") strtok(NULL, "") 直到结束,然后执行 strtok( poly_buffer, "")///

查看 strtok 的运行时引用文档

关于C++ strtok问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2229774/

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