如何在流字符数组编辑元素 [英] How to edit an element in a streaming char array
本文介绍了如何在流字符数组编辑元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有(用popen(),而不是文件的网络数据)都在为const char从与fgets进来记录*阵列格式。
I have records coming in from fgets (web data using popen(), not a file) that are in const char * array format.
const char * cstr = buff;
第3项是字符串,并且需要被移除或被改变到零。
我如何进入第3个元素一个const char *数组流增量为5?
The 3rd item is a string and needs to either be removed or changed to a zero. How do I access the 3rd element in a const char * array stream in increments of 5?
1
2
string
4
5
1
2
string
4
5
code:
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)
error: no match and : error: assignment of read-only location '*(cstr2 + 2u)'
你如何正确地访问3元素在字符流字符数组?
How do you correctly access the 3rd element in a char streaming char array?
推荐答案
此溶液previously发表匿名:
This solution was previously posted by anonymous:
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
}
这篇关于如何在流字符数组编辑元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文