如何使用 c++ 将值检索到数组中

How to retrieve a value into an array using c++?

本文关键字:数组 检索 何使用 c++      更新时间:2023-10-16

我试图在数组中搜索来自服务器 java 的值。服务器在单击按钮后发送数据,并将此值接收到estratto这是一个字符数组。我需要在字符串数组numeri或字符串变量中找到estratto number.

我该怎么做?

这是我的代码:

char estratto[2048];
int pos=-1;
char message[2048] = "";
//-- some code
while(recv(sock, buff, sizeof(buff),0) > 0){
            strcat(message,buff); // received message form client
        }
//-- some code
//-- divided message into a string array
istringstream iss(message);
    string token;
    string numeri[15];
    int i=0,j=0,e=0;
    while (std::getline(iss, token, ','))
    {
        numeri[i]= token.c_str();
        i++;
    }

//-- the part that has problems
    string number(message);
    while(recv(sock, estratto, sizeof(estratto),0)>0){          
                for(i=0; i<15; i++){
                    pos=number.find(estratto);
                    if(pos>0)
                        cout<<"TROVATO!"<<endl; 
                    if(strcmp(numeri[i].c_str(),estratto)==0){
                        trovati_cartella[i]=1;
                        cout<<"TROVATO!"<<endl;         
                    }
                }
            }

cout <<"Trovato!"<<endl;如果我尝试更改此代码的某些部分,则不起作用。有人可以帮助我找到解决方案吗?

您是否遇到了无符号与有符号字符集问题。您可能需要使用 64 位编码标准对字符串进行编码和解码。

我会像这样修改代码:

while(recv(sock, estratto, sizeof(estratto),0)>0){          
            for(i=0; i<15; i++){
                pos=number.find(estratto);
                if(pos != std::string::npos)
                    cout<<"TROVATO!"<<endl; 
                if(strstr(numeri[i].c_str(),estratto) != NULL){
                    trovati_cartella[i]=1;
                    cout<<"TROVATO!"<<endl;         
                }
            }
        }

您的第一个检查"pos>0"是错误的,因为如果从索引 0 开始的数字字符串中包含 estratto 字符串,您的检查将找不到它。相反,strcmp() 函数的第二次检查只会在 estratto 字符串完全匹配时捕获 estratto 字符串,但如果它是子字符串,则不会。