2013-08-24 4 views
-2

Когда я принимаю std::istringstream iss(std::move(result_string)); внутри, а затем он дает ошибку. На самом деле я получаю свою строку result_string внутри, поэтому мне нужно выполнить move.пересекает инициализацию 'std :: istringstream iss' при использовании внутри цикла while

я могу инициализировать ISS так: std::istringstream iss

Теперь Как я могу выполнить операцию перемещения переназначить буфер из строки (result_string) на поток? означает, как я могу выполнить (std::move(s)) внутри?

мой исходный код:

std::string s = "one two two three one one two"; 
std::istringstream iss(std::move(s)); 
     while (iss >> s) 
    { 
     int tmp = ++s1[s]; 
     if (tmp == max_count) 
     { 
      most.push_back(s); 
     } 
     else if (tmp > max_count) 
     { 
      max_count = tmp; 
      most.clear(); 
      most.push_back(s); 
     } 
    } 

Но когда весь код в то время как цикл, он дает ошибку.

это весь код, если вы хотите увидеть:

#include <fcntl.h> 
#include <string.h> 
#include <stdlib.h> 
#include <errno.h> 
#include <stdio.h> 
#include <netinet/in.h> 
#include <resolv.h> 
#include <sys/socket.h> 
#include <arpa/inet.h> 
#include <fcntl.h> 
#include <string.h> 
#include <stdlib.h> 
#include <iostream> 
#include <stdio.h> 
#include <netinet/in.h> 
#include <resolv.h> 
#include <sys/socket.h> 
#include <unistd.h> 
#include <vector> 
#include <sstream> 
#include <algorithm> 
#include <unordered_map> 
#include <pthread.h>       
#include <iostream> 
#include <sstream> 
#include <cstdio> 
#include "dictionary.h" 
#pragma GCC diagnostic ignored "-Wwrite-strings" 
using namespace std; 
void *SocketHandler(void *); 

int main(int argv, char **argc) 
{ 
    int host_port = 1103; 
    char buf[20]; 
    int k; 
    struct sockaddr_in my_addr; 
    int hsock; 
    int *p_int; 
    int err; 
    socklen_t addr_size = 0; 
    int *csock; 
    sockaddr_in sadr; 
    pthread_t thread_id = 0; 

    hsock = socket(AF_INET, SOCK_STREAM, 0); 
    if (hsock == -1) { 
    printf("Error initializing socket %dn", errno); 
    goto FINISH; 
    } 

    p_int = (int *) malloc(sizeof(int)); 
    *p_int = 1; 

    if ((setsockopt(hsock, SOL_SOCKET, SO_REUSEADDR, (char *) p_int, sizeof(int)) == -1) || (setsockopt(hsock, SOL_SOCKET, SO_KEEPALIVE, (char *) p_int, sizeof(int)) == -1)) { 
    printf("Error setting options %dn", errno); 
    free(p_int); 
    goto FINISH; 
     } 
    free(p_int); 

    my_addr.sin_family = AF_INET; 
    my_addr.sin_port = htons(host_port); 

    memset(&(my_addr.sin_zero), 0, 8); 
    my_addr.sin_addr.s_addr = INADDR_ANY; 

    if (bind(hsock, (sockaddr *) & my_addr, sizeof(my_addr)) == -1) { 
    fprintf(stderr, "Error binding to socket, make sure nothing else is listening on this port %dn", errno); 
    goto FINISH; 
    } 
    if (listen(hsock, 10) == -1) { 
    fprintf(stderr, "Error listening %dn", errno); 
    goto FINISH; 
    } 
    //Now lets do the server stuff 

    addr_size = sizeof(sockaddr_in); 

    while (true) { 
    printf("waiting for a connectionn\n"); 
    csock = (int *) malloc(sizeof(int)); 
    if ((*csock = accept(hsock, (sockaddr *) & sadr, &addr_size)) != -1) { 
     printf("---------------------nReceived connection from %s\n", inet_ntoa(sadr.sin_addr)); 
     pthread_create(&thread_id, 0, &SocketHandler, (void *) csock); 
     pthread_detach(thread_id); 
    } else { 
     fprintf(stderr, "Error accepting %dn", errno); 
    } 
    } 

    FINISH: 
    ; 
} 
void *SocketHandler(void *lp) 
{ 
    int ar[2]; 
    int result=0; 
    int *csock = (int *) lp; 
    char buf[20]; 
    int k; 
    char *skp; 
    char *str; 
    char *str2; 

    std::string ss; 
    std::ostringstream bfr; 
    std::string result_string; 
    std::vector<std::string> most; 
    int max_count = 0; 
    typedef std::unordered_map<std::string,int> occurrences; 
    occurrences s1; 

    int pcount = 0, ncount = 0; 
    char buffer[1024]; 
    int buffer_len = 1024; 
    int bytecount; 

    int i = 0,t=0,q=0; 
    int j = 0; 
    char *ch[50] = { 0 }; /* stores references to 50 words. */ 
    char *ch2[50] = { 0 }; 
    char *excluded_string[50] = { 0 }; 

     char *word = strtok(buffer, " "); 
     char *word2 = strtok(buffer, " "); 

     char *portstring1=(char *)malloc(sizeof(buffer)); 
     char *portstring2=(char *)malloc(sizeof(buffer)); 

    memset(buffer, 0, buffer_len); 
    if ((bytecount = recv(*csock, buffer, buffer_len, 0)) == -1) { 
    fprintf(stderr, "Error receiving data %d \n", errno); 
    goto FINISH; 
    } 
    printf("Received bytes %d \nReceived string %s \n ", bytecount, buffer); 
    word = strtok(buffer, " "); 

    while ((NULL != word) && (50 > i)) { 
    ch[i] = strdup(word); 
    excluded_string[j]=strdup(word); 
    word = strtok(NULL, " "); 
    skp = BoyerMoore_skip(ch[i], strlen(ch[i])); 
    if(skp != NULL) 
    { 
     i++; 
     continue; 
    } 
    printf("exclueded : %s and %s size %d \n",excluded_string[j],ch[i],sizeof(excluded_string)); 
    bfr << excluded_string[j] << " "; 
    result_string = bfr.str(); 
    j++;  
    // std::cout << "string is :" << r1; 
    str = BoyerMoore_positive(ch[i], strlen(ch[i])); 
    str2= BoyerMoore_negative(ch[i], strlen(ch[i])); 
    if (str == NULL) 
     t++; 
    else { 
     pcount += 1; 
    } 

    if(str2== NULL) 
     q++; 
    else 
     ncount += 1; 

    i++; 
    if(str==NULL && str==NULL and skp !=NULL) 
    { 
     pcount=0; 
     ncount=0; 
    } 
    } 
     std::cout << "string is :" << result_string << "\n"; 
    std::istringstream iss(std::move(result_string)); 

     //extract the string till endl, get count values for each word and word with max count value 
     while (iss >> result_string) 
     { 
      int tmp = ++s1[result_string]; 
      if (tmp == max_count) 
      { 
       most.push_back(result_string); 
      } 
      else if (tmp > max_count) 
      { 
       max_count = tmp; 
       most.clear(); 
       most.push_back(result_string); 
      } 
     } 

     std::cout << std::endl << "Maximum Occurrences" << std::endl; 
    for (std::vector<std::string>::const_iterator it = most.cbegin(); it != most.cend(); ++it) 
      std::cout << *it << std::endl; 


    ar[0]=pcount; 
    ar[1]=ncount; 

    if ((bytecount = send(*csock, (char *)ar, 2 *sizeof(int), 0)) == -1) { // Here we cant send lenth-1. It consider exact 
    fprintf(stderr, "Error sending data %d\n", errno); 
    goto FINISH; 
    } 

    FINISH: 
    free(csock); 
    return 0; 
} 
+1

Что такое 'строка (result_string)' и откуда оно взялось? Неясно, что вы хотите сделать с этой строкой или как она связана с потоком. –

+0

@NicolBolas: Его строка, которую я получаю после обработки и вызова функции. В приведенном выше коде я взял его непосредственно как 's' – user123

+1

Непонятно, как выглядит ваш код, который * не работает *. Вы должны опубликовать то, что сломано, а не то, что работает. –

ответ

1

Вопрос справедлив, но не действует на StackOverflow.com. Вы должны задать этот вопрос на форуме. См. Правила.

Проблема заключается здесь:

std::string s = "one two two three one one two"; 
std::istringstream iss(std::move(s)); 
    while (iss >> s) 
    { 
     int tmp = ++s1[s]; 

Вы пытаетесь инициализировать переменную (интермедиат TMP) в цикле в то время. Если вы компьютер, то это то, что вы видите: выполните цикл while с условием (правильно), инициализируйте новую переменную tmp с этим вычислением. Как только цикл переходит ко второй итерации, вы говорите ему: «Инициализируйте новую переменную tmp с этим вычислением», но tmp уже был инициализирован, и поэтому это ошибка.

Решение:

std::string s = "one two two three one one two"; 
std::istringstream iss(std::move(s)); 
    int tmp; 
    while (iss >> s) 
    { 
     tmp = ++s1[s]; 
+0

Видимо, он «не должен», он получил ответ прямо от Диппо. –

+1

Как вы это понимаете? Что он не должен спрашивать о кодере?Поскольку это будет правильно, я вижу SO как faq, а не форум. Кроме того, http://codereview.stackexchange.com/ было бы лучше спросить код. – Dippo

+0

Это была шутка. Я согласен с вашим советом о том, что вопрос плохой, я просто комментировал тот факт, что вы все равно ответили. –

Смежные вопросы