gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 01:47:21 29 4
gpt4 key购买 nike

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

关于C++ istream - 如何读取带空格的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19270763/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com