字符串流转换错误

stringstream conversion error

本文关键字:错误 转换 字符串      更新时间:2023-10-16

我曾经在一个类中使用过以下代码片段。今天,我把它复制到另一个班上。编译时,我出现了以下错误。真奇怪竟然发生了这样的事!你能告诉我怎么回事吗?非常感谢。

我刚刚使用以下代码片段在一个演示项目中进行了测试。我跑得很有魅力!

int main()
{  
   char buffer[] = "I1 I2 V1 V2 I3 V3 I4 DO V4";
   std::stringstream s(buffer); 
   std::istream_iterator<std::string> begin(s); 
   std::istream_iterator<std::string> end; 
   std::vector<std::string> IVector;
   std::vector<std::string> VVector;
   for ( ; begin != end; ++begin) 
   {     
       std::string sElem = *begin;
       switch((*begin)[0])
       {  
          case 'I':
            IVector.push_back( sElem);
            break;
          case 'V':
            VVector.push_back( sElem);
            break;
          default:
           ;
       }
   }
   return 0;
}
void ClassifyChannel(char* szBuffer)
{   
    // Empty vectors
    m_svIRChannels.clear();
    m_svVISChannels.clear();
    std::stringstream s(szBuffer); 
    std::istream_iterator<std::string> itBegin(s); 
    std::istream_iterator<std::string> itEnd; 
    for (; itBegin != itEnd; ++itBegin) 
    {     
        std::string sElem = *itBegin;
        // Switch on first character
        switch ((*itBegin)[0])
        {  
           // Infrared channel, such as IR1, IR2, IR3 (WV), and IR4
           case 'I':
           case 'W':
              // Insert into IR channel vector here 
              m_svIRChannels.push_back(sElem);
              break;
           // Visible channels, such as VIS, and VIS1KM
           case 'V':
              // Insert into VIS channel vector here 
              m_svVISChannels.push_back(sElem);
              break;
        }
    } 
} 

错误消息为

error C2440: 'initializing' : cannot convert from 'std::string' to 'int'
1>        No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
1>f:tipstipsfy2hdf5dataiohandler.cpp(830) : error C2664: 'std::istream_iterator<_Ty>::istream_iterator(std::basic_istream<_Elem,_Traits> &)' : cannot convert parameter 1 from 'int' to 'std::basic_istream<_Elem,_Traits> &'
1>        with
1>        [
1>            _Ty=std::string,
1>            _Elem=char,
1>            _Traits=std::char_traits<char>
1>        ]
1>        and
1>        [
1>            _Elem=char,
1>            _Traits=std::char_traits<char>
1>        ]    

您使用的是什么编译器?你的代码片段在我的盒子上用VC10编译得很好。你忘了包括所有正确的头文件了吗?对于这段代码,你需要这3个标题:

#include <string>
#include <sstream>
#include <iterator>

由于VC10、<iterator>不被其他人隐式地包括。你需要自己把它包括在内。

我的猜测;你没有明确地做

#include <string>

IO流头只有std::string的前向声明,但这在您的情况下是不够的。尝试显式地包含string标头来解决此问题。

#include <sstream> 

需要包含。

我在VS2017和VS2019中尝试过,它通过包含此标头来工作。

以下是我尝试过的示例代码。

int main()
{
    string line = "asasas asasas asasas asasas must try";
    stringstream check1(line);
}