/*
I am trying to understand the intricacies of invalid user input to a statement like "cin >> x" where x is of some data type.
I wrote the following function, "PrintBuffer" to print the internal
buffer of cin.
Here is a run of the program
$ ./a.out
Enter Double
xx2.5yy
You entered x = 0
xx2.5yy
^C
$
It sort of worked, it showed the buffer but not the final newline and it
hung so I had to ^C to end the program.
My question is, how do I fix the function?
Thank you,
Joe
*/
================================================
#include <iostream>
using namespace std;
void PrintBuffer(istream &s)
{
cout << s.rdbuf() << "--" << endl;
}
int main()
{
double x{17.5};
cout << "Enter Double" << endl;
cin >> x;
cout << "You entered x = " << x << endl;
PrintBuffer(cin);
return 0;
}
On Wednesday, 10 November 2021 at 10:50:58 UTC+2, Joseph Hesse wrote:
/*
I am trying to understand the intricacies of invalid user input to a
statement like "cin >> x" where x is of some data type.
I wrote the following function, "PrintBuffer" to print the internal
buffer of cin.
Here is a run of the program
$ ./a.out
Enter Double
xx2.5yy
You entered x = 0
xx2.5yy
^C
$
It sort of worked, it showed the buffer but not the final newline and it
hung so I had to ^C to end the program.
My question is, how do I fix the function?
Thank you,
Joe
*/
================================================
#include <iostream>
using namespace std;
void PrintBuffer(istream &s)
{
cout << s.rdbuf() << "--" << endl;
}
int main()
{
double x{17.5};
cout << "Enter Double" << endl;
cin >> x;
cout << "You entered x = " << x << endl;
PrintBuffer(cin);
return 0;
}
Posted program shouldn't produce described output. The "--" is clearly missing from that. Maybe you run some other program or some
previous version of it that was designed to hung?
On Wednesday, 10 November 2021 at 10:50:58 UTC+2, Joseph Hesse wrote:
/*
I am trying to understand the intricacies of invalid user input to a
statement like "cin >> x" where x is of some data type.
I wrote the following function, "PrintBuffer" to print the internal
buffer of cin.
Here is a run of the program
$ ./a.out
Enter Double
xx2.5yy
You entered x = 0
xx2.5yy
^C
$
It sort of worked, it showed the buffer but not the final newline and it
hung so I had to ^C to end the program.
My question is, how do I fix the function?
Thank you,
Joe
*/
================================================
#include <iostream>
using namespace std;
void PrintBuffer(istream &s)
{
cout << s.rdbuf() << "--" << endl;
}
int main()
{
double x{17.5};
cout << "Enter Double" << endl;
cin >> x;
cout << "You entered x = " << x << endl;
PrintBuffer(cin);
return 0;
}
Posted program shouldn't produce described output. The "--" is clearly missing from that. Maybe you run some other program or some
previous version of it that was designed to hung?
Better solution:
#include <iostream>
#include <charconv>
#include <utility>
#include <cstring>
#include <limits>
using namespace std;
int main()
{
auto parseDouble = []( string const &str ) -> double
{
double value;
from_chars_result fcr = from_chars( str.c_str(), str.c_str() + strlen(
str.c_str() ), value );
if( fcr.ec != errc() || *fcr.ptr )
return std::numeric_limits<double>::quiet_NaN();
return value;
};
cout << "enter value" << endl;
string dStr;
cin >> dStr;
double d = parseDouble( dStr );
if( isnan( d ) )
{
cout << "invalid value" << endl;
return EXIT_FAILURE;
}
cout << "you entered: " << d << endl;
}
Better use C++17's from_chars().
#include <iostream>
#include <charconv>
#include <utility>
#include <cstring>
using namespace std;
int main()
{
    auto parseDouble = []( char const *str ) -> pair<bool, double>
    {
       double value;
       from_chars_result fcr = from_chars( str, str + strlen( str ), value );
       if( fcr.ec != errc() || *fcr.ptr )
           return pair<bool, double>( false, 0.0 );
       return pair<bool, double>( true, value );
    };
    cout << "enter value" << endl;
    string dStr;
    cin >> dStr;
    pair<bool, double> pd = parseDouble( dStr.c_str() );
    if( !pd.first )
    {
       cout << "invalid value" << endl;
       return EXIT_FAILURE;
    }
    cout << "you entered: " << pd.second << endl;
}
` formatted input.
On Wed, 10 Nov 2021 15:31:52 +0100
Bonita Montero <Bonita.Montero@gmail.com> wrote:
Better solution:
#include <iostream>
#include <charconv>
#include <utility>
#include <cstring>
#include <limits>
using namespace std;
int main()
{
auto parseDouble = []( string const &str ) -> double
{
double value;
from_chars_result fcr = from_chars( str.c_str(), str.c_str() + strlen(
str.c_str() ), value );
if( fcr.ec != errc() || *fcr.ptr )
return std::numeric_limits<double>::quiet_NaN();
return value;
};
cout << "enter value" << endl;
string dStr;
cin >> dStr;
double d = parseDouble( dStr );
if( isnan( d ) )
{
cout << "invalid value" << endl;
return EXIT_FAILURE;
}
cout << "you entered: " << d << endl;
}
Or alternatively dump most of that over complicated crap and just use strtof()
C++ reinventing the wheel once aqain.
On 10 Nov 2021 15:11, Bonita Montero wrote:
Better use C++17's from_chars().
#include <iostream>
#include <charconv>
#include <utility>
#include <cstring>
using namespace std;
int main()
{
     auto parseDouble = []( char const *str ) -> pair<bool, double>
     {
        double value;
        from_chars_result fcr = from_chars( str, str + strlen( str ),
value );
        if( fcr.ec != errc() || *fcr.ptr )
            return pair<bool, double>( false, 0.0 );
        return pair<bool, double>( true, value );
     };
     cout << "enter value" << endl;
     string dStr;
     cin >> dStr;
     pair<bool, double> pd = parseDouble( dStr.c_str() );
     if( !pd.first )
     {
        cout << "invalid value" << endl;
        return EXIT_FAILURE;
     }
     cout << "you entered: " << pd.second << endl;
}
When you parse the input string you can use `std::getline` instead of
Conversely, when you use `>>` you can let `>>` parse the input.` formatted input.
I see no advantage in both using `>>` and parsing the input.
using namespace std;
Joseph Hesse <joeh@gmail.com> wrote:
using namespace std;
Out of curiosity, where did you learn to write that?
Am 10.11.2021 um 18:12 schrieb DozingDog@thekennel.co:
On Wed, 10 Nov 2021 15:31:52 +0100
Bonita Montero <Bonita.Montero@gmail.com> wrote:
Better solution:
#include <iostream>
#include <charconv>
#include <utility>
#include <cstring>
#include <limits>
using namespace std;
int main()
{
auto parseDouble = []( string const &str ) -> double
{
double value;
from_chars_result fcr = from_chars( str.c_str(), str.c_str() + strlen(
str.c_str() ), value );
if( fcr.ec != errc() || *fcr.ptr )
return std::numeric_limits<double>::quiet_NaN();
return value;
};
cout << "enter value" << endl;
string dStr;
cin >> dStr;
double d = parseDouble( dStr );
if( isnan( d ) )
{
cout << "invalid value" << endl;
return EXIT_FAILURE;
}
cout << "you entered: " << d << endl;
}
Or alternatively dump most of that over complicated crap and just use >strtof()
C++ reinventing the wheel once aqain.
Does it parse non-parseable values into a NaN ?
Because I'm fascinated by what I find to be a rather odd psychological aversion that many people have towards the "std::" prefix, usually for
no logical nor rational reason.
I'm also curious about how "using namespace std;" became so ubiquitous.
On 11/11/21 08:54, Juha Nieminen wrote:
Joseph Hesse <joeh@gmail.com> wrote:
using namespace std;
Out of curiosity, where did you learn to write that?
I don't remember where I first learned it. I've been writing C++
programs on and off for the last 20 years. In order to avoid writing
lots of "std::cout" kind of statements I use it. I wouldn't use it in production code. The code I presented was just to test something.
Out of curiosity, why do you ask?
On Thu, 11 Nov 2021 07:33:09 +0100
Bonita Montero <Bonita.Montero@gmail.com> wrote:
Am 10.11.2021 um 18:12 schrieb DozingDog@thekennel.co:
On Wed, 10 Nov 2021 15:31:52 +0100strtof()
Bonita Montero <Bonita.Montero@gmail.com> wrote:
Better solution:
#include <iostream>
#include <charconv>
#include <utility>
#include <cstring>
#include <limits>
using namespace std;
int main()
{
auto parseDouble = []( string const &str ) -> double
{
double value;
from_chars_result fcr = from_chars( str.c_str(), str.c_str() + strlen(
str.c_str() ), value );
if( fcr.ec != errc() || *fcr.ptr )
return std::numeric_limits<double>::quiet_NaN();
return value;
};
cout << "enter value" << endl;
string dStr;
cin >> dStr;
double d = parseDouble( dStr );
if( isnan( d ) )
{
cout << "invalid value" << endl;
return EXIT_FAILURE;
}
cout << "you entered: " << d << endl;
}
Or alternatively dump most of that over complicated crap and just use
C++ reinventing the wheel once aqain.
Does it parse non-parseable values into a NaN ?
Why not read the man page. You check the pointer return values instead, no isnan() required.
I don't see any big difference when using strtof.
It would result in almost the same code.
Bonita Montero <Bonita.Montero@gmail.com> wrote:
Am 11.11.2021 um 12:42 schrieb Juha Nieminen:
Because I'm fascinated by what I find to be a rather odd psychological
aversion that many people have towards the "std::" prefix, usually for
no logical nor rational reason.
Writing using namespace std is ok ! People know std::'s symbols
and no library writer has his own symbols that collide with std::.
Using the std:: prefix make the code easier to understand.
Am 11.11.2021 um 12:42 schrieb Juha Nieminen:
Because I'm fascinated by what I find to be a rather odd psychological
aversion that many people have towards the "std::" prefix, usually for
no logical nor rational reason.
Writing using namespace std is ok ! People know std::'s symbols
and no library writer has his own symbols that collide with std::.
You're compulsive and intolerant. It's just a matter of taste.
Actually what strtof() accepts as input depends on the current locale,
while the input format of from_chars() is fixed and does not depend
on the locale.
This can seriously bite you in the posterior when you assume that,
for example, the decimal point of the ascii representation of the
number will be a '.'. The locale might change strtof() to assume
it's ',' instead, and you'll get weird results (where the
decimal part isn't parsed, and ends the parsing at the dot.)
On 11/11/21 8:11 AM, Juha Nieminen wrote:
...
Actually what strtof() accepts as input depends on the current locale,
while the input format of from_chars() is fixed and does not depend
on the locale.
This can seriously bite you in the posterior when you assume that,
for example, the decimal point of the ascii representation of the
number will be a '.'. The locale might change strtof() to assume
it's ',' instead, and you'll get weird results (where the
decimal part isn't parsed, and ends the parsing at the dot.)
Or, you can get precisely the results you desire, if you're reading
digit strings in the format that's appropriate to the current locale.
The solution, as always, it to make sure that the current locale is the correct one for what you're currently trying to do.
Am 10.11.2021 um 18:12 schrieb Dozi...@thekennel.co:...
Or alternatively dump most of that over complicated crap and just use strtof()
C++ reinventing the wheel once aqain.
Does it parse non-parseable values into a NaN ?
On Thursday, November 11, 2021 at 1:33:27 AM UTC-5, Bonita Montero wrote:
Am 10.11.2021 um 18:12 schrieb Dozi...@thekennel.co:...
Or alternatively dump most of that over complicated crap and just use strtof()
C++ reinventing the wheel once aqain.
The C++ standard defines std::stof() as calling std::strtof() when passed a narrow
string, and it defines std::num_get<>::do_get() as calling std::strtof() if the final
argument is a float. Therefore, C++ is not reinventing the wheel, it's re-using the
wheel invented by C.
Does it parse non-parseable values into a NaN ?
That doesn't make sense - if it's non-parseable, how could it be parsed?
Am 11.11.2021 um 16:58 schrieb james...@alumni.caltech.edu:...
On Thursday, November 11, 2021 at 1:33:27 AM UTC-5, Bonita Montero wrote:
Does it parse non-parseable values into a NaN ?
That doesn't make sense - if it's non-parseable, how could it be parsed?NaN might be a proper representation for invalid values depending on
what you're parsing.
Rest of your nonsense unread.
On Thursday, November 11, 2021 at 11:06:54 AM UTC-5, Bonita Montero wrote:
Am 11.11.2021 um 16:58 schrieb james...@alumni.caltech.edu:...
On Thursday, November 11, 2021 at 1:33:27 AM UTC-5, Bonita Montero wrote:
NaN might be a proper representation for invalid values depending onDoes it parse non-parseable values into a NaN ?
That doesn't make sense - if it's non-parseable, how could it be parsed?
what you're parsing.
If it's not parseable, a parsing function other than strtof() might produce a NaN
anyway - but by definition it could not do so by parsing it, but only by recognizing it
as unparseable. However, as specified in the text I cited from the standard, that's not
what strtof() does with unparseable input - it's required to return 0.
strtof() can produce a NaN, but to make that happen you have to pass it a parseable string starting with an optional + or - sign, and followed by either NAN
or NAN(n-char-sequence).
The n-char-sequence can carry an arbitrary mix of digits and nondigits. Contrary from what you might conclude from the name. a nondigit is not defined as
"anything that isn't a digit". Rather, nondigits are defined by 6.2.4.1p2 as including only
' _', a-z or A-Z.
Am 10.11.2021 um 17:20 schrieb Alf P. Steinbach:
On 10 Nov 2021 15:11, Bonita Montero wrote:
Better use C++17's from_chars().
#include <iostream>
#include <charconv>
#include <utility>
#include <cstring>
using namespace std;
int main()
{
     auto parseDouble = []( char const *str ) -> pair<bool, double> >>>      {
        double value;
        from_chars_result fcr = from_chars( str, str + strlen( str >>> ), value );
        if( fcr.ec != errc() || *fcr.ptr )
            return pair<bool, double>( false, 0.0 );
        return pair<bool, double>( true, value );
     };
     cout << "enter value" << endl;
     string dStr;
     cin >> dStr;
     pair<bool, double> pd = parseDouble( dStr.c_str() );
     if( !pd.first )
     {
        cout << "invalid value" << endl;
        return EXIT_FAILURE;
     }
     cout << "you entered: " << pd.second << endl;
}
When you parse the input string you can use `std::getline` instead of
Conversely, when you use `>>` you can let `>>` parse the input.` formatted input.
I see no advantage in both using `>>` and parsing the input.
How get parsing-errors signalled when using getline […]
[…] or operator >> ?
/*
I am trying to understand the intricacies of invalid user input to a statement like "cin >> x" where x is of some data type.
I wrote the following function, "PrintBuffer" to print the internal
buffer of cin.
Here is a run of the program
$ ./a.out
Enter Double
xx2.5yy
You entered x = 0
xx2.5yy
^C
$
It sort of worked, it showed the buffer but not the final newline and it
hung so I had to ^C to end the program.
My question is, how do I fix the function?
Thank you,
Joe
*/
================================================
#include <iostream>
using namespace std;
void PrintBuffer(istream &s)
{
cout << s.rdbuf() << "--" << endl;
}
int main()
{
double x{17.5};
cout << "Enter Double" << endl;
cin >> x;
cout << "You entered x = " << x << endl;
PrintBuffer(cin);
return 0;
}
I'm also curious about how "using namespace std;" became so ubiquitous.
Why did its use spread like a wildfire, and persists to this day?
Where do people learn it? Why do people use it? Is it cargo cult
programming? Do people just see it being used in tutorials and examples,
and start repeating it with no second thought about it? Why does there
seem to be such a strong instinct to write that line in order to get
rid of the "std::" prefix? You see it all the time, and it just puzzles
me where this tidbit of habit comes from and how people learn it.
It is so as Bjarne Stroustrup teached that with his examples from day he added namespaces into C++ programming language .
On Thursday, 11 November 2021 at 13:42:29 UTC+2, Juha Nieminen wrote:
I'm also curious about how "using namespace std;" became so ubiquitous.
Why did its use spread like a wildfire, and persists to this day?
Where do people learn it? Why do people use it? Is it cargo cult
programming? Do people just see it being used in tutorials and examples,
and start repeating it with no second thought about it? Why does there
seem to be such a strong instinct to write that line in order to get
rid of the "std::" prefix? You see it all the time, and it just puzzles
me where this tidbit of habit comes from and how people learn it.
It is so as Bjarne Stroustrup teached that with his examples from day he added namespaces into C++ programming language .
Now Bjarne's coding guidelines suggest narrowing the usage of it somewhat ... <http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rs-using>
... but no one apparently reads that.
Additionally there now are innumerable "competitive programming sites"
like TopCoder, CodeForces, CodeChef, CodeGolf where C++ participants habitually start their works with two lines:
#include <bits/stdc++.h>
using namespace std;
/*
I am trying to understand the intricacies of invalid user input to a statement like "cin >> x" where x is of some data type.
I wrote the following function, "PrintBuffer" to print the internal
buffer of cin.
Here is a run of the program
$ ./a.out
Enter Double
xx2.5yy
You entered x = 0
xx2.5yy
^C
$
It sort of worked, it showed the buffer but not the final newline and it
hung so I had to ^C to end the program.
My question is, how do I fix the function?
Thank you,
Joe
*/
================================================
#include <iostream>
using namespace std;
void PrintBuffer(istream &s)
{
cout << s.rdbuf() << "--" << endl;
}
int main()
{
double x{17.5};
cout << "Enter Double" << endl;
cin >> x;
cout << "You entered x = " << x << endl;
PrintBuffer(cin);
return 0;
}
On 11 Nov 2021 23:12, Öö Tiib wrote:
On Thursday, 11 November 2021 at 13:42:29 UTC+2, Juha Nieminen wrote:
I'm also curious about how "using namespace std;" became so ubiquitous.
Why did its use spread like a wildfire, and persists to this day?
Where do people learn it? Why do people use it? Is it cargo cult
programming? Do people just see it being used in tutorials and examples, >>> and start repeating it with no second thought about it? Why does there
seem to be such a strong instinct to write that line in order to get
rid of the "std::" prefix? You see it all the time, and it just puzzles
me where this tidbit of habit comes from and how people learn it.
It is so as Bjarne Stroustrup teached that with his examples from day he
added namespaces into C++ programming language .
Now Bjarne's coding guidelines suggest narrowing the usage of it
somewhat ...
<http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rs-using>
... but no one apparently reads that.
Additionally there now are innumerable "competitive programming sites"
like TopCoder, CodeForces, CodeChef, CodeGolf where C++ participants
habitually start their works with two lines:
#include <bits/stdc++.h>
using namespace std;
`using namespace std;` is commonly used because it's practical for small programs; a work saver.
Adoption of that practice in other cases, e.g. in the global namespace
in a header, happens because people use simple behavior patterns without understanding them. Much like applying the brakes after driving at high
speed into a hairpin turn. Nowadays car automation (ABS) may prevent the
most serious consequences, but that wasn't so when I learned to drive.
One can argue that such people should not be coding in C++, and I
believe that Bjarne originally assumed that such people would not be
coding in C++. Maybe that C++ users would be like the programmers he
knew at AT&T Bell Labs. But the language became just too popular,
analogous to the eternal September of Usenet.
- Alf
11.11.2021 15:32 James Kuyper kirjutas:
On 11/11/21 8:11 AM, Juha Nieminen wrote:
...
Actually what strtof() accepts as input depends on the current locale,
while the input format of from_chars() is fixed and does not depend
on the locale.
This can seriously bite you in the posterior when you assume that,
for example, the decimal point of the ascii representation of the
number will be a '.'. The locale might change strtof() to assume
it's ',' instead, and you'll get weird results (where the
decimal part isn't parsed, and ends the parsing at the dot.)
In practice one should use functions like strtof() for locale-specific things, and functions like from_chars() for fixed data formats. As an
extra bonus, the latter often work significantly faster.
?? Tiib <ootiib@hot.ee> wrote:
It is so as Bjarne Stroustrup teached that with his examples from day he
added namespaces into C++ programming language .
I suppose that explains a lot.
On Fri, 2021-11-12, Juha Nieminen wrote:
?? Tiib <ootiib@hot.ee> wrote:
It is so as Bjarne Stroustrup teached that with his examples from day he >>> added namespaces into C++ programming language .
I suppose that explains a lot.
I don't know: I don't see lots of people read his books[1].
I also don't think he ever taught 'using namespace std' ... but The
C++ Programming Language examples /do/ omit the prefix, and perhaps it doesn't explain clearly why.
Perhaps the psychology behind it is closely related to the psychology
behind so many programmers using variable and function names that are needlessly short to the point of being detrimental to the readability
and understandability of the code.
(I think one quintessential example of this is POSIX: If you look at
all the names, function names, macro names, variable names... defined
by POSIX, you'll notice a clear pattern of brevity over clarity in many cases. Sure, POSIX itself is not really to blame here, because it simply officially standardized what was an bunch of unofficial "standards",
and it just took most of the existing stuff as-is, without wanting to
change it, for backwards compatibility. However, regardless of who is responsible for those names, it just quite clearly shows the brevity-over-clarity psychology behind it.)
On Fri, 2021-11-12, Juha Nieminen wrote:
?? Tiib <ootiib@hot.ee> wrote:
It is so as Bjarne Stroustrup teached that with his examples from day he >>> added namespaces into C++ programming language .
I suppose that explains a lot.
I don't know: I don't see lots of people read his books[1].
I also don't think he ever taught 'using namespace std' ... but The
C++ Programming Language examples /do/ omit the prefix, and perhaps it doesn't explain clearly why.
/Jorgen
[1] Except me. I like his writing and I think I'm heavily influenced
by his style, which I find blends well with Unix styles.
Sysop: | Keyop |
---|---|
Location: | Huddersfield, West Yorkshire, UK |
Users: | 113 |
Nodes: | 8 (1 / 7) |
Uptime: | 05:17:23 |
Calls: | 2,497 |
Calls today: | 14 |
Files: | 8,644 |
Messages: | 1,902,088 |