当我尝试使用istringstream从输入中提取有效数字时,我从istringstream中得到了以下不良行为:
例如:

void extract(void)
{
double x;
string line, temp;

getline(cin, line);
istringstream is(line);
while(is >>temp)
{
    if(istringstream(temp) >>x)
        {std::cout<<"number read: "<<x<<endl;}
}

}

输入:1 2 3rd 4th
输出:
number read: 1
number read: 2
number read: 3
number read: 4

异常行为是istringstream将字符串3rd转换为数字3。
为什么istringstream可以做到这一点,又如何避免呢?

最佳答案

这是因为您从流中读取了数字。
>>运算符从流中提取"3rd",并尝试将其转换为double,但是由于只有字符串的第一个字符是数字,因此它只能解析"3"并简单地丢弃非数字字符。

如果需要"3rd",则需要将其作为字符串读取。

关于c++ - istringstream转换的不当行为,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27421575/

10-12 20:32