繁体   English   中英

C ++ istream-如何使用空格读取字符串

[英]C++ istream - how to read string with whitespace

在下面的小程序中,我想用空格读取inputString:

#include <string>
#include <sstream>
#include <iostream>


int main( int argc , char ** argv ) {
   std::string inputString(" ITEM ");
   std::istringstream inputStream( inputString );

   //Template:

   T value;

   inputStream.unsetf(std::ios::skipws);
   inputStream >> value;

   std::cout << "Value: [" << value << "]" << std::endl;
   std::cout << "StringPos: " << inputStream.tellg() << std::endl;
   std::cout << "State: " << inputStream.good() << std::endl;
}

产生输出:

Value: []
StringPos: -1
State: 0

如果删除unsetf()调用,则会得到:

Value: [ITEM]
StringPos: 4
State: 1

即如预期的那样当空白被忽略时。 所以-很明显,“不要跳过空白”设置有误。 有小费吗?

编辑:添加类似模板的“ T值”后,该示例不再编译。 但重要的是

inputStream >> value;

作品。 以下元代码也应该工作:

if is_string(T)
   value = inputString;   // String values are assigned directly
else 
   inputStream >> value;  // Other types.

乔金 -

采用:

std::string line;
if(std::getline(inputStream, line)) {
    // line contains one line from the input stream
} else {
    // inputStream is empty, EOF or in error state
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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