如何在cplusplus中重用istringstream

how to reuse istringstream in cplusplus

本文关键字:istringstream cplusplus      更新时间:2023-10-16

我想重用istringstream变量。使用构造函数初始化istringstream变量很容易。但是当我尝试使用=<<将其重新分配给新值时,我得到了错误。我正在使用c++11。在vs2015中使用=似乎没有编译错误。但是gcc 4.8.2(在Centos 6.4 x86_64上的devtools-2)得到错误。

代码如下:

std::string line;
int simmulationtimes; double InitialIDensity;
// deploy configuration file
std::ifstream config(configfile);
if (!config.is_open())
{
       return false;
}
std::getline(config, line);
std::istringstream sline(line);
std::string sInitialIDensity;
while(std::getline(sline, sInitialIDensity, '=')); 
InitialIDensity = std::stod(sInitialIDensity);
std::getline(config, line);
std::string ssimmulationtimes;
sline.str("");  sline.clear();
sline = std::istringstream(line);
while (std::getline(sline, ssimmulationtimes, '='));
simmulationtimes = std::stoi(ssimmulationtimes);

配置文件应该是:

IDensity=0.5
times=5
错误:

error: no match for ‘operator=’ (operand types are ‘std::istringstream {aka std::basic_istringstream<char>}’ and ‘std::string {aka std::basic_string<char>}’)
  sline = std::istringstream(line);

解决方案(如如何初始化-a-stdstringstream)在stackoverflow上重用stringstream不适合我。关于重用istringstream有什么想法吗?谢谢您的考虑。

使用str()方法将新的std::string设置为现有的std::istringstream