I'm trying to examine a C++ code from my tutorial book. I've written this using CodeBlocks IDE:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
/*...*/
using namespace std;
/*...*/
int main (void){
cout << "Please enter name and age: \n\n:>";
string _sInput = "";
int _intInput = -1;
cin >> _sInput >> _intInput;
cout << "Hello " << _sInput << "!\n";
cout << "You have aged " << _intInput << " years.";
}
Based on what was discussed in the book by Mr. Stroustrup, now that I have given the variable _intInputan intial value, if I input wrong data like James Boy I am supposed to receive an output like this:
Hello James!
You have aged -1 years.
But what I get is You have aged 0 years. just like the time I have not given an intial value.
Is there anything wrong with my code or what?!
Since C++11, when reading integer or floating point number from istream fails, the target variable is set to 0. See this (cppreference.com) or this (stack overflow.com) for more on that.
This means, you can't use a sentinel value to detect parse error, you have to use for example fail() method to check if there was some error.
As per C++11, the value is set to zero, when an error occurs. See "If extraction fails, zero is written to value and failbit is set. If extraction results in the value too large or too small to fit in value..." for more info.
Related
Introduction
I am trying to code a converter for bin/oct/dec/hex numbers in c++. At first I print a message in a console asking the user to insert the type of conversion he wants to do and, followed by the cin that allows him to enter the conversion and then i ask him for the number followed by the cin that allows him to enter the number.
My problem
My problem is that after the user inserts the conversion, the variable gets printed on the console without me telling it that.
What I've Tried
I looked on the docs and in their example they do it like this:
cout << "Please enter an integer value: ";
cin >> i;
cout << "The value you entered is " << i;
cout << " and its double is " << i*2 << ".\n";
And that is similar to my code(which you will see below).
I also tried to do getline(cin, type) but still the variables would get printed without me coding that.
My code
Faulty code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string type;
int n;
cout << "Insert what type of conversion you want to make(binoct, bindec, binhex, octbin, octdec, octhex, decbin, decoct, dechex, hexbin, hexoct, hexdec): ";
cin >> type;
cout << "Insert the number you want to convert: ";
cin >> n;
return 0;
}
Input
binoct
1001
Output
Insert what type of conversion you want to make(binoct, bindec, binhex,octbin, octdec, octhex, decbin, decoct, dechex,hexbin, hexoct, hexdec):binoct
binoct
Insert the number you want to convert:1001
1001
Expected output:
Insert what type of conversion you want to make(binoct, bindec, binhex,octbin, octdec, octhex, decbin, decoct, dechex,hexbin, hexoct, hexdec):binoct
Insert the number you want to convert:1001
Additional notes
I should mention that before this version of the code I did use cout to print my variables to see if it works but i re-built the code a few times and now there's no cout << type or cout << n inside my code
I looked on stackoverflow and I didn't seem to see anything similar, if this is a duplicate I apologize.
The code is fine, either clean and rebuild your project, or it has something to do with your project / debug settings, that print out the value.
Try Building and Running the Program in release mode.
Here is an example code demonstrating the problem I'm facing.
#include <iostream>
#include <string>
extern "C" {
#include <unistd.h>
}
int main()
{
std::cout << "Making tests ready!" << std::endl;
std::cout << "\nTo start out, Enter an integer: ";
int a = 0;
std::cin >> a;
std::string input;
sleep(3); // what to do if user enters data during this?
std::cout << "\n Now enter a string";
std::getline(std::cin, input);
std::cout << "\nHere are your values - " << a << " & " << input;
return 0;
}
See the sleep call in between the code? This could be replaced with somewhat long delays while computing something when my program isn't accepting any inputs. Now if user presses some keys during this time, that input is captured by std::getline() in next line of code. I know this is the default behavior since it should capture the input being provided.
But what I want is to clear all that captured input and start fresh with 15th line that is std::cout << "\n Now enter a string";, which is immediately after sleep. I don't know exact term to describe this or else I would have used that. Thanking you.
Edit: I've tried using std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); in my code, but it asks for input and then discards it.
Please mind my english, not a native speaker.
Reading the comments causes me to think that you can't really solve this problem (at least by the means suggested there). There's an inherent race condition in any case. Consider the following lines:
sleep(3);
// (*) <- Potential location 1.
std::cout << "\n Now enter a string";
// (**) <- Potential location 2.
std::getline(std::cin, input);
The various comments show some (very technically-competent) ways to flush the standard input. The problem is, you cannot put them in the location marked (*) nor (**).
First location - you clear the standard input some way. Now you decide it's time to move to the next line (std::cout << ...). While you do that, the user types in some more input. Race!
Second location - You print out the message (std::cout << ...), and proceed to clear the standard input. Before you manage to do that, the user typed in something. Race!
It seems to me that any of the techniques described in the comment require locking the standard input, and I don't think there's a (standard) way to do so.
This question already has answers here:
std::cin input with spaces?
(8 answers)
Closed 8 years ago.
The code is not giving desired output
when I type in a string example "Ben Parker", the output is "Goodmorning, Ben" and not the entire name("Ben Parker") what seems to be the problem?
#include <iostream>
#include <stdlib.h>
#include <cstring>
int main() {
char your_name[20];
std::cout << "Enter your name: ";
std::cin >> your_name;
std::cout << "Goodmorning, ";
std::cout.write (your_name, strlen(your_name)) << std::endl;
return 0;
}
SOLUTION
This was a very old question when I just began programming.
The entire character array can be read and printed with a for loop, or better a string type variable can be used, since it is C++.
using string your_name; seems to fix the problem, which can be then printed with a simple std::cout << your_name << endl;
You probably put a space in between "Ben" and "Parker" in input. This would cause the cin logic to believe it had an answer after seeing the space following "Ben". You will probably want to read an entire line at a time to get past that problem. See this page for an example.
My code is this:
#include <iostream>
int main()
{
using namespace std;
const float dollar = 1.00;
cout << "You have " << dollar*10.00 << " dollars." << endl;
cin.get();
cin.get();
return 0;
}
I am a beginner to c++. I typed this code just playing around and assumed that the console would display "You have 10.00 dollars, but it actually displays that I have "10" and not "10.00" dollars. Could someone tell me why this is?
Since you are dealing with dollar amounts, you can set the following before writing to cout:
std::cout.precision(2);
std::cout.setf(std::ios::fixed);
Live code example at coliru
#include <iostream>
int main() {
using namespace std;
const float dollar = 1.00;
std::cout.precision(2);
std::cout.setf(std::ios::fixed);
cout << "You have " << dollar*10.00 << " dollars." << endl;
cin.get();
cin.get();
return 0;
}
The standard library already has some code to deal with monetary values. In C++98/03, it's sufficiently painful to use that it's probably not worth the trouble, but in C++11, a couple of I/O manipulators were added that make them quite easy to use.
In the default "C" locale, they probably won't be of much use, but in a nationalized locale, they will format money as you'd normally expect for that locale. For example:
#include <iostream>
#include <iomanip>
int main(){
long double amt;
std::cin.imbue(std::locale(""));
std::cout.imbue(std::locale(""));
std::cin >> std::get_money(amt);
std::cout << std::put_money(amt) << "\n";
}
This uses the "" locale, which chooses a locale based on how the OS is configured. For example, in my case the OS is set up for US English, so that chooses the US English locale.
Based on the locale, this displays the money as (the programmers guess) money would normally be displayed in that locale. For example, if I enter "10" (with or without some 0's after the decimal point), it prints the value out as 10.00.
If I prefer, I can specify a locale--for example, I can specify "de" to get a German locale. In this case, the value will (at least with the compiler I have handy) be printed out using German conventions (. as a thousands separator and , as a decimal separator). Also note that I can specify the locale for std::cin separately from the locale for std::cout, so I can (for example) set cin to US English, and cout to German. If I do so, I can enter 1,234,567.89 as the input, and receive 1.234.567,89 as the output. (Note that although it converts the formatting from US to German convention, it does not automatically convert my input in dollars to Euros at output).
Note that put_money also automatically restores the previous formatting after it does its thing. For example, if I change the last line above to: std::cout << std::put_money(amt) << "\n";, then enter 10 as the input, I get 10.00 10.
Also note that (at least with VC++) std::get_money actually stores the value as an integer count of cents, which will prevent most rounding errors. So, if I enter 10 what's actually stored is 1000, which is then re-scaled to display as 10.00 at output.
If you're stuck with an older compiler that doesn't include std::get_money and std::put_money, it's probably easiest to just copy their definitions from the standard, put them into a header of your own, and use them anyway. If you don't want to do that, I'd consider defining a money class that stores an amount of money, and overloads operator>> and (especially) operator<< to handle formatting as you see fit, so writing out a monetary value would be something like:
money m(10);
std::cout << m;
...and the operator<< would handle all the std::setprecision and such to display that with two places after the decimal point and such.
If you don't format output, cout will cut unnecessary zeroes. You can set precision of output.
cout<<fixed<<setprecision(2)<<dollar<<endl;
//cout << setprecision(3) << fixed;
Also one more point dont put
using namespace std; inside the main statement,
Add header #include
//Code //
int main()
{
float dollar = 2.00f;
cout << setprecision(3) << fixed;
std::cout << dollar << " dollars." << endl;
cin.get();
cin.get();
return 0;
}
when I am trying to run this snippet of code I am getting some malfunctions I have not been able to pinpoint the cause of. The first two "cout" lines display the numbers 7 and 3, however, the last "cout" line displays numbers ranging from 50-60 usually (At the moment when I run it I get 55 and 51, which seems to somehow correlate a bit with the numbers I am trying to read). As far as I can tell from some googling and the books I have at hand this should be valid, but there's obviously something I am missing. Thank you for your time.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string text = "73";
int one=0, two=0;
cout << text.at(0) << endl;
cout << text.at(1) << endl;
one = text.at(0);
two = text.at(1);
cout << one << endl << two << endl;
return 0;
}
the program functions correctly: text.at() returns a char, which you implicitly convert to an int. Then you print the value of that int, which are respectively 55 for "7" and 51 for "3" (look here).