2012-02-03 58 views
1

下面的代码有很多输出字符串在最后我试图推回到avector并将其追加到一个字符串,所以然后我可以返回它,但它只获得最后一个字符串是输出我需要得到他们所有。插入向量C++

什么我doign错了,这样我可以推回的所有字符串

DCS_LOG_DEBUG("--------------- Validating .X/ ---------------") 
std::string str = el[i].substr(3); 
std::vector<std::string>st; 
split(st,str,boost::is_any_of("/")); 
boost::regex const string_matcher(splitMask[0]); 
if(boost::regex_match(st[0],string_matcher)) 
{ 
    a = "Correct Security Instruction\n"; 
} 
else 
{ 
    a = "Incorrect Security Instruction\n" 
} 


boost::regex const string_matcher4(splitMask[4]); 
if(boost::regex_match(st[4],string_matcher4)) 
{ 
    a = "Correct Autograpgh\n" 
} 
else 
{ 
    a = "Incorrect Autograpgh\n" 
} 

boost::regex const string_matcher5(splitMask[5]); 
if(boost::regex_match(st[5],string_matcher5)) 
{ 
    a = "Correct Free text\n"; 

} 
else 
{ 
    a = "Incorrect Free text\n" 
} 

std::vector<std::string>::iterator it; 
std::string s = (""); 
output.push_back(a); 
i++; 

for(it = output.begin(); it < output.end(); it++) 
{ 
    s+= *it; 
} 

return s; 
+4

你的代码中只有一个'push_back',你为什么期望你的向量包含多个字符串? – Mat 2012-02-03 15:50:22

+0

也许如果我追加字符串然后@Mat – CodersSC 2012-02-03 15:58:37

+0

你也不追加字符串。 – Mat 2012-02-03 16:00:01

回答

1

分配不止一次a更将取代,不串联。你正在寻找什么,更有可能输出流(或输出迭代器)。

建议简化:

DCS_LOG_DEBUG("--------------- Validating .X/ ---------------") 
std::string str = el[i].substr(3); 
std::vector<std::string> st; 
split(st,str,boost::is_any_of("/")); 
boost::regex const string_matcher(splitMask[0]); 
boost::regex const string_matcher4(splitMask[4]); 
boost::regex const string_matcher5(splitMask[5]); 

std::ostringstream oss; 

oss << (boost::regex_match(st[0],string_matcher)? "correct":"incorrect") << " Security Instruction\n"; 
oss << (boost::regex_match(st[4],string_matcher4)? "correct":"incorrect") << " Autograpgh\n"; 
oss << (boost::regex_match(st[5],string_matcher5)? "correct":"incorrect") << " Free text\n"; 

return oss.str(); 

包括<sstream>std::ostringstream

+0

我的投票简洁明了:) – qdot 2012-02-03 18:55:48

0

你确定你所得到的结果不只是第一个字符串?

这就是说,它并不完全清楚你想要做什么,但假设在你发布的东西上面有一些循环代码,似乎你的问题与for循环的定位有关。

  while(i < el.size()) //Assuming something like this 
     {     
       ... 

       else 
       { 
        a = "Incorrect Free text\n" 
       }    
       output.push_back(a); 
       i++; 
      } 
      //move this stuff out of the loop so that it only runs after you have 
      // processed all the strings in el 
      std::vector<std::string>::iterator it; 
      std::string s = (""); 
      for(it = output.begin(); it < output.end(); it++) 
      { 
      s+= *it; 
      } 
      return s; 
     }