简体   繁体   中英

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

I tried to search into an array a value coming from a server java.The server send data after a click on a button and this value is received into estratto which is a char array. I need to find estratto into the string array numeri or into the string variable number .

How can I do this?

Here's my code:

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;         
                    }
                }
            }

The cout <<"Trovato!" << endl; doesn't work if I try to change some parts of this code. Someone can help me to find the solution?

Are you running into a unsigned vs signed character set issue. You may need to encode and decode the string with the 64 bit encoding standard.

I would modify the code like this:

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;         
                }
            }
        }

Your first check "pos>0" is wrong because if estratto string is contained into number string starting from index 0, your check will not find it. Your second check by strcmp() function instead would catch estratto string only if it exactly matches numeri[i] string, but not if it is a substring.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM