C++ istream - 如何读取带有空格的字符串

C++ istream - how to read string with whitespace

本文关键字:空格 字符串 读取 istream 何读取 C++      更新时间:2023-10-16

在下面的小程序中,我想读取带有空格的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
}