1

I'm trying to read strings and floats from stdin but I'm running into a weird issue. When reading certain characters the input is "consumed" and lost before being read as a string. I'm expecting that any characters would flip the fail bit and then get cleared allowing the character to be read as a string.

float fl;
string str;
while (std::getline(std::cin, line))
{
    std::istringstream iss(line);
    while (iss.good())
    {
        if (iss >> fl)
        {
            std::cout << "read: " << fl << "\n";
        }
        else
        {
            iss.clear();
            if (iss >> str)
            {
                std::cout << "read: " << str << "\n";
            }
        }
    }
}

Here's the output I'm getting. You can see that certain characters, a-f for example aren't being read as strings after failing to be read as floats.

a
b
c
d
e
f
g
read: g
h
read: h
i
j
read: j
k
read: k
l
read: l
m
read: m
n
o
read: o
p
q
read: q
r
read: r
s
read: s
t
read: t
u
read: u
v
read: v
w
read: w
x
y
read: y
z
read: z
12.0
read: 12
12.33
read: 12.33

When I change fl to an integer everything works perfectly, no issues reading certain characters. I can read ints/strings with no problem. Does this have anything to do with special float formats or reading the float as a hex?

I'm on OSX Apple LLVM version 10.0.1 (clang-1001.0.46.4) I tried using a different compiler and it works.

anatolyg
  • 26,506
  • 9
  • 60
  • 134
  • Wouldn't be better to read the input as a string and then parse if its a float or not instead of relying on the `std::istringstream::operator >>` return? – André Caceres Feb 16 '20 at 07:31
  • I saw that mentioned elsewhere but I thought that this would be cleaner since it's less code. If this ends up not working I'll probably go that route. I'd still like to know why certain letters aren't working though. – user12906245 Feb 16 '20 at 07:42
  • This works on gcc 9.1. Which compiler are you using? – theWiseBro Feb 16 '20 at 08:08
  • The example works fine on `gcc 7.4.0` – Tarek Dakhran Feb 16 '20 at 08:31
  • I'm on OSX Apple LLVM version 10.0.1 (clang-1001.0.46.4) I tried using a different compiler and it works! I just realized that it's still happening for single "+" and "-" characters though. – user12906245 Feb 16 '20 at 08:33
  • The single `+` and `-` characters are consumed by the line `if (iss >> fl)` even though it fails to extract a `float`. Perhaps `if(iss.tellg() > 0) iss.seekg(-1, std::ios::cur);` before you try extracting a string would work. [example](https://godbolt.org/z/PVcXfy) – Ted Lyngmo Feb 16 '20 at 09:41

0 Answers0