In this tutorial, they say we should do this:
#include <iostream>
#include <string>
#include <sstream>
int main ()
{
std::string stringLength;
float inches = 0;
float yardage = 0;
std::cout << "Enter number of inches: ";
std::getline (std::cin,stringLength);
std::stringstream(stringLength) >> inches;
std::cout<<"You entered "<<inches<<"\n";
yardage = inches/36;
std::cout << "Yardage is " << yardage;
return 0;
}
However, this:
#include <iostream>
#include <string>
#include <sstream>
int main ()
{
float inches = 0;
float yardage;
std::cout << "Enter number of inches: ";
std::cin >> inches;
std::cout<<"You entered "<<inches<<"\n";
yardage = inches/36;
std::cout << "Yardage is " << yardage<<"\n";
return 0;
}
works for me.
However I'm a beginner so I guess there is something I'm missing but I can't see why. Some might say it's useful to keep the string stringLength so that I can handle cases where the user wouldn't input a float but rather abc
, but I'm sure I could do it without using <sstream>
(by checking character by character in stringLength if it's only digits or the character .
for example).
Or even like this:
#include <iostream>
#include <limits>
int main() {
double inches;
double yardage;
while (true) {
std::cout << "Enter inches: ";
if (std::cin >> inches) {
std::cout << "You entered " << inches << "\n";
yardage = inches / 36;
std::cout << "Yardage is " << yardage << "\n";
break;
} else {
std::cout << "Invalid input. Trying again..." << std::endl;
std::cin.clear(); // Clear the error state
// Ignore the rest of the input buffer
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
}
return 0;
}
Yes indeed, sstream
could mean I don't have to flush the input buffer, but is this really good enough to justify its use? Or am I missing something?
#include <iostream>
#include <sstream>
int main() {
std::string stringLength;
float inches;
float yardage;
while (true) {
std::cout << "Enter inches: ";
std::getline (std::cin,stringLength);
if (std::stringstream(stringLength) >> inches){
std::cout<<"You entered "<<inches<<"\n";
yardage = inches/36;
std::cout << "Yardage is " << yardage;
break;
}
else {
std::cout << "Invalid number, please try again\n";
}
}
return 0;
}