gpt4 book ai didi

c++ - 如何编辑流式字符数组中的元素

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:51:56 27 4
gpt4 key购买 nike

我有来自 fgets 的记录(使用 popen() 的网络数据,而不是文件),这些记录采用 const char * 数组格式。

const char * cstr = buff;

第三项是字符串,需要删除或更改为零。如何以 5 为增量访问 const char * 数组流中的第三个元素?

1
2
string
4
5
1
2
string
4
5

代码:

while(fgets(buff, sizeof buff, fp) != NULL)
{
const char * cstr2 = buff;
for(int i = 0; i < 5; ++i){
if(i == 3){
if (!strcmp(cstr2, "Buy\n")) {
printf("Found One!\n");
cstr2[2] = 0;
}
if (!strcmp(cstr2, "Sell\n")) {
printf("Found Two!\n");
cstr2[2] = 0;
}
}
}
}

预期输出:

1
2
0
4
5
1
2
0
4
5

错误:没有匹配和:错误:分配只读位置“*(cstr2 + 2u)”

如何正确访问 char 流式 char 数组中的第三个元素?

最佳答案

此解决方案之前由匿名发布:

char* getmyData()
{
char buff[BUFSIZ];
FILE *fp = popen("php getMyorders.php 155", "r");
if (fp == NULL) perror ("Error opening file");
size_t size = 1000;
char* data = (char*)malloc(size);
char* ptr = data;
std::string::size_type sz;
int i=0;
while(fgets(buff, sizeof(buff), fp) != NULL)
{
const char * cstr2 = buff;
const char* test = ptr;
//for(int i = 0; i < 5; ++i)
{
if(i == 2){
if (!strcmp(cstr2, "Buy\n")) {
printf("Found One!\n");
strcpy(ptr,"0\n");
//ptr+=2;
}
else
if (!strcmp(cstr2, "Sell\n")) {
printf("Found Two!\n");
strcpy(ptr,"0\n");
//ptr+=2;
}
else
{
strcpy(ptr,cstr2);
ptr+=strlen(cstr2);
}
}
else
{
strcpy(ptr,cstr2);
ptr+=strlen(cstr2);
}

try
{
int nc = std::stod (test,&sz);
std::cout << "Test: " << 1+nc << "\n";
}
catch(...)
{
}

i++;
if (i==5)
i=0;


}

if (ptr-data+100>=size)
{
int ofs = ptr-data;
size*=2;
data = (char*)realloc(data,size);
ptr = data+ofs;
}
}
return data; // DONT FORGET TO call free() on it
}

关于c++ - 如何编辑流式字符数组中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26996472/

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