int i;
cin>>i;
cout<<i
when we entered Character i.e 'A' why it gives Zero output ?
Because A is not a numeric value suitable for storing in an integer, so it will leave your integer alone, as shown here:
#include <iostream>
int main (void) {
int i = 12345;
std::cin >> i;
std::cout << i << std::endl;
return 0;
}
When you run that code and enter A, it outputs 12345 as the value doesn't change.
If you want truly robust input, it's usually better to input lines as strings then convert them yourself.
"Mickey-mouse" programs or those where you have total control over the input can use the sort of input methods you're using, serious code should use more suitable methods.
If your intent is to convert an input character into its integer code, you can use something like:
#include <iostream>
int main (void) {
char c;
std::cin >> c;
std::cout << (int)c << std::endl;
return 0;
}
You should always check if the operation succeeded before continuing.
int i;
if (cin >> i)
cout << i;
else
cout << "Not a valid number!";
because the value 'A' is not stored in the variable i since it is a integer variable. i believe that is the reason the initial value 12345 is printed on the screen...
Related
I was working on a HackerRank problem and I could not figure out why the C++ code round the double values when I am adding them and why it does not take in/print the entire string input it is given.
The code is supposed to take in an integer input (from one line), a double input (from another line), and a string input (also, from another line). Then it is supposed to print out the sum of the int input and 4, the sum of the double input and 4.0, and concatenate the string "HackerRank" to the beginning of the input string.
Here's the code I have:
#include <iostream>
#include <iomanip>
#include <limits>
int main(){
int i = 4;
double d = 4.0;
string s = "HackerRank";
// Declare second integer, double, and String variables.
// Read and save an integer, double, and String to your variables.
// Note: If you have trouble reading the entire string, please go back and review the Tutorial closely.
// Print the sum of both integer variables on a new line.
// Print the sum of the double variables on a new line.
// Concatenate and print the String variables on a new line
// The 's' variable above should be printed first.
int a;
double b;
string c;
cin >> a;
cin >> b;
cin >> c;
a = a + i;
b = b + d;
cout << a << endl;
cout << b << endl;
cout << "" + s + c;
return 0;
}
For the following input:
12
4.0
is the best place to learn and practice coding!
I got the output:
16
8
HackerRank is
When this is the expected output:
16
8.0
HackerRank is the best place to learn and practice coding!
The answer to your 2 questions:
Firstly, when you add a value of type int to a value of type float/string, the result will be of type int. This explains why you the output is 8 and not 8.0. This same rule applies to multiplication, division, and subtraction. Whenever an int is operated on by a float/double value or vice versa, the result is always of type int. Therefore, you should change the initialization of your d value to:
double d = 4.0; // Or float d = 4.0
By the way, you cannot add a decimal point to a value of type int and expect it to be a floating point/double value. The data type of the variable that stores the value must be defined/initialized with a certain data type.
Secondly, your code does not print the desired string as you are using the wrong function to get the string as input from the user. While cin is the norm to be used in input, it does not work so well with variables of type "string". The reason for this is because cin only accepts one word; one continuous int, floating point value, char, etc..., and it cannot accept an entire sentence with spaces in between because it just stops reading after it sees a space; that's the rules of cin. To bypass this problem, you'll need another function, and that is
getline(cin, variable_to_store_data);
instead of doing:
cin >> c;
Do this:
getline(cin, c);
This way, the entire sentence you inputted will be stored in the variable and not just the first word of the sentence. The getline does not ignore the words in a sentence that come after the first one; it reads all of the user input till the point he/she hits Enter, and it then stores the entire value in the variable (that's the second parameter).
By the way, if you want to output multiple things in one cout line, then do it using the following template:
cin << a << ... << z << endl; // endl is optional; depends on your needs
Avoid using the method you used above:
cout << "" + s + c;
Do it this way:
cout << "" << s << c; // Why do you have "" at the begninning? That prints nothing. You can take that off also.
On a side note, getline() also has a lot of other functions, such as reading lines from a file. Read more about it online; there are lots of resources available.
Hope this answers your question.
EDIT: To make the program work, you'll actually have to add another line to ignore the enter hit at the end of the cin >> b; command, because that saves as the string in c. Therefore, do this:
cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');
getline(cin, c);
The line I just added ignores the newline character hit at the end of the cin >> b command. This way, the compiler goes on to ask the user for the string to be stored in c. I've tried this code, and it works as it should.
Another thing, change your output statement to;
cout << "" << s << " " << c << "." << endl;
This makes the string easier to read, and it adds a space between variable s and variable c during output. Hope this helps!
This code will work...
#include<iostream>
#include<string.h>
using namespace std;
int main()
{
int i = 4;
double d = 4.0;
string s = "HackerRank ";
int i2;
double d2;
string s2;
cin>>i2;
cin>>d2;
cin.ignore();
getline(cin, s2);
cout<<i2+i<<endl;
cout.precision(1);
cout << fixed << d+d2 << endl;
cout<<s+s2;
return 0;
}
You can use the function 'getline' to realize it.
And the following example is well done on VS2013.
#include <string>
#include <iostream>
using namespace std;
int main(){
string c;
getline(cin, c); // is there anybody ?
cout << "Hello, " + c; // Hello, is there anybody ?
system("pause");
return 1;
}
cin>>b;
use cin.ignore();
and then getline(cin, string_name);
This will read the complete string.
I'm a newbie to C++. Small code sample follows:
int main(int argc, char* argv[]) {
char ch1;
int int1;
cin >> ch1;
cin >> int1;
cout << ch1 << '\n';
cout << int1 << '\n';
return 0;
}
When I run the program and input the following:
az
I get as output:
a
32767
I understand the 'a' but why the integer value of 32767? I just want to test and see what happen if instead of a numeric value assigned to int1 i used a 'z'.
I try inputting:
ax
...and I also get same results.
Now if instead of int int1 I use short int1 and run the program with input:
az
I get the output:
a
0
P.S.
sizeof(int) = 4
sizeof(short) = 2
I am using a 64-bit machine.
When an input stream fails to read valid data, it doesn't change the value you passed it. 'z' is not a valid number, so int1 is being left unchanged. int1 wasn't initialized, so it happened to have the value of 32767. Check the value of cin.fail() or cin.good() after reading your data to make sure that everything worked the way you expect it to.
cin >> int1; means "read an integer and put it in int1." So you feed it z, which is not a valid character in an integer, and it simply aborts the read and leaves whatever in int1.
Test this by initializing int1 to something and seeing what happens.
The c++ cin stream is doing input validation for the program.
When streaming from cin into an int cin will only accept valid number didgits, -0123456789, and also only values between INT_MIN and INT_MAX.
If the numerical value for z (122) is required I would recommend using the c getchar function rather than the cin stream.
int main(int argc, char* argv[]) {
cout << "function main() .." << '\n';
char ch1 = getchar();
int int1 = getchar();
cout << ch1 << '\n';
cout << int1 << '\n';
return 0;
}
When az is input this will output
a
122
Using cin directly is, personally, i.e., for me, a bad idea for reading data in non-trivial programs. I suggest you read another answer I gave for a similar question:
C++ character to int
This question already has answers here:
Infinite loop with cin when typing string while a number is expected
(4 answers)
Closed 3 years ago.
I'm learning C++ and writing little programs as I go along. The following is one such program:
// This program is intended to take any integer and convert to the
// corresponding signed char.
#include <iostream>
int main()
{
signed char sch = 0;
int n = 0;
while(true){
std::cin >> n;
sch = n;
std::cout << n << " --> " << sch << std::endl;
}
}
When I run this program and keep inputs at reasonably small absolute values, it behaves as expected. But when I enter larger inputs, e.g., 10000000000, the program repetitively spits out the same output. Some combinations of input cause erratic behavior. For example:
#: ./int2ch
10
10 -->
10000000000
10 -->
10 -->
10 -->
10 -->
The program spits out "10 --> " until it's killed. (With this particular sequence of inputs, the program's output changes speed erratically.) I also noticed that the output of large values is determined by the previous legal input as well as the value of the current illegal input.
What's going on? (I don't care about fixing the program, that's easy. I want to understand it.)
Basically your cin stream is in a fail state and thus returns immediately when you try to read it. Rewrite your example like this:
#include <iostream>
int main()
{
signed char sch = 0;
int n = 0;
while(std::cin >> n){
sch = n;
std::cout << n << " --> " << sch << std::endl;
}
}
cin >> n will return a reference to cin, which you can test for "good-ness" in a conditional. So basically the the "while(std::cin >> n)" is saying "while i could still read from standard input successfully, do the following"
EDIT: the reason it repeatedly output the last good value entered is because that was the last value successfully read in n, the failed reads won't change the value of n
EDIT: as noted in a comment, you can clear the error state and try again something like this would probably work and just ignore bad numbers:
#include <iostream>
#include <climits>
int main() {
signed char sch = 0;
int n = 0;
while(true) {
if(std::cin >> n) {
sch = n;
std::cout << n << " --> " << sch << std::endl;
} else {
std::cin.clear(); // clear error state
std::cin.ignore(INT_MAX, '\n'); // ignore this line we couldn't read it
}
}
}
Yes, Evan Teran pointed out most things already. One thing i want to add (since i cannot comment his comment yet :)) is that you must put the call to istream::clear before the call to istream::ignore. The reason is that istream::ignore likewise will just refuse to do anything if the stream is still in the fail state.
Given that you are on a 32 bit machine, 10000000000 is too big a number to be represented by an int. Also converting an int to a char will only give you from 0..255 or -128..127 depending on the compiler.
One problem here is that a char has a size of one byte, and thus can only hold a number between -127 and 128. An int on the other hand, is typically 4 bytes, and can take on much larger values. Second problem is that you are inputting a value that is too large even for an int.
So I am currently learning C++ and decided to make a program that tests my skills I have learned so far. Now in my code I want to check if the value that the user enters is a double, if it is not a double I will put a if loop and ask them to reenter it. The problem I have is how do I go about checking what type of variable the user enters, ex- if a user enters a char or string, I can output an error message. Here is my code:
//cubes a user entered number
#include <iostream>
using namespace std;
double cube(double n); //function prototype
int main()
{
cout << "Enter the number you want to cube: "; //ask user to input number
double user;
cin >> user; //user entering the number
cout << "The cube of " << user << " is " << cube(user) << "." << endl; //displaying the cubed number
return 0;
}
double cube (double n) //function that cubes the number
{
return n*n*n; // cubing the number and returning it
}
Edit: I would have to say I just started and don't have the slightest of clue about your code, but I will check out your link. By the way, I haven't learned how to work with templates yet,I am learning about dealing with data, only Chapter 3 in my C++ Primer Plus 5th edition.
Safe C++ Way
You can define a function for this using std::istringstream:
#include <sstream>
bool is_double(std::string const& str) {
std::istringstream ss(str);
// always keep the scope of variables as close as possible. we see
// 'd' only within the following block.
{
double d;
ss >> d;
}
/* eat up trailing whitespace if there was a double read, and ensure
* there is no character left. the eof bit is set in the case that
* `std::ws` tried to read beyond the stream. */
return (ss && (ss >> std::ws).eof());
}
To assist you in figuring out what it does (some points are simplified):
Creation of a input-stringstream initialized with the string given
Reading a double value out of it using operator>>. This means skipping whitespace and trying to read a double.
If no double could be read, as in abc the stream sets the fail-bit. Note that cases like 3abc will succeed and will not set the fail-bit.
If the fail-bit is set, ss evaluates to a zero value, which means false.
If an double was read, we skip trailing whitespace. If we then are at the end of the stream (note that eof() will return true if we tried to read past the end. std::ws does exactly that), eof will return true. Note this check makes sure that 3abc will not pass our check.
If both cases, right and left of the && evaluate to true, we return true to the caller, signaling the given string is a double.
Similar, you check for int and other types. If you know how to work with templates, you know how to generalize this for other types as well. Incidentally, this is exactly what boost::lexical_cast provides to you. Check it out: http://www.boost.org/doc/libs/1_37_0/libs/conversion/lexical_cast.htm.
C Way One
This way has advantages (being fast) but also major disadvantages (can't generalized using a template, need to work with raw pointers):
#include <cstdlib>
#include <cctype>
bool is_double(std::string const& s) {
char * endptr;
std::strtod(s.c_str(), &endptr);
if(endptr != s.c_str()) // skip trailing whitespace
while(std::isspace(*endptr)) endptr++;
return (endptr != s.c_str() && *endptr == '\0');
}
strtod will set endptr to the last character processed. Which is in our case the terminating null character. If no conversion was performed, endptr is set to the value of the string given to strtod.
C Way Two
One might thing that std::sscanf does the trick. But it's easy to oversee something. Here is the correct way to do it:
#include <cstdio>
bool is_double(std::string const& s) {
int n;
double d;
return (std::sscanf(s.c_str(), "%lf %n", &d, &n) >= 1 &&
n == static_cast<int>(s.size()));
}
std::sscanf will return the items converted. Although the Standard specifies that %n is not included in that count, several sources contradict each other. It's the best to compare >= to get it right (see the manpage of sscanf). n will be set to the amount of the processed characters. It is compared to the size of the string. The space between the two format specifiers accounts for optional trailing whitespace.
Conclusion
If you are a beginner, read into std::stringstream and do it the C++ way. Best not mess with pointers until you feel good with the general concept of C++.
There is no suitable way to check if a string really contains a double within the standard library. You probably want to use Boost. The following solution is inspired by recipe 3.3 in C++ Cookbook:
#include <iostream>
#include <boost/lexical_cast.hpp>
using namespace std;
using namespace boost;
double cube(double n);
int main()
{
while(true)
{
cout << "Enter the number you want to cube: ";
string user;
cin >> user;
try
{
// The following instruction tries to parse a double from the 'user' string.
// If the parsing fails, it raises an exception of type bad_lexical_cast.
// If an exception is raised within a try{ } block, the execution proceeds
// with one of the following catch() blocks
double d = lexical_cast <double> (user);
cout << "The cube of " << d << " is " << cube(d) << "." << endl;
break;
}
catch(bad_lexical_cast &e)
{
// This code is executed if the lexical_cast raised an exception; We
// put an error message and continue with the loop
cout << "The inserted string was not a valid double!" << endl;
}
}
return 0;
}
double cube (double n)
{
return n*n*n;
}
sscanf can do what you want; it returns the number of arguments properly processed. This should get you started:
//cubes a user entered number
#include <iostream>
#include <cstdio>
using namespace std;
double cube(double n); //function prototype
int main()
{
cout << "Enter the number you want to cube: "; //ask user to input number
string user;
cin >> user; //user entering the number
// Convert the number to a double.
double value;
if(sscanf(user.c_str(), "%lf", &value) != 1)
{
cout << "Bad! " << user << " isn't a number!" << endl;
return 1;
}
cout << "The cube of " << user << " is " << cube(user) << "." << endl; //displaying the cubed number
return 0;
}
double cube (double n) //function that cubes the number
{
return n*n*n; // cubing the number and returning it
}
Other methods posted in other answers have their advantages and disadvantages. This one has issues with trailing characters and isn't "C++"-y.
I would have to say I just started and don't have the slightest of clue about your code, but I will check out your link. By the way, I haven't learned how to work with templates yet,I am learning about dealing with data, only Chapter 3 in my C++ Primer Plus 5th edition.
You can fall back on C and use strtod
You program reads in a string and then passes it to a function that attempts to convert the string into double.
bool is_double(const char* strIn, double& dblOut) {
char* lastConvert = NULL;
double d = strtod(strIn, &lastConvert);
if(lastConvert == strIn){
return false;
} else {
dblOut = d;
return true;
}
}
Code:
int a;
cin>>a;
cout<<a<<endl;
Then I use g++ test.cpp, and run it. Then I input a letter 'b' to the variable a. The output is 0.
But, When I test the Other code:
cout<<int('b')<<endl; // output: 98
Why? What is the different?
std::cin is an object, an instance of a std::istream. std::istream has overloaded the >> to support a variety of types. One of those types is &int. When there is a std::istream on the left of >> and an integer reference on the right, the method istream& operator>> (int& val) is called. The conceptual implementation of that method is as follows.
Store 0 in an accumulator
Read a character of the input
If the character is 0-9, add its decimal value to the accumulator
If not, return the value of the accumulator
Return to step 2
When you provide 'b' as input to istream& operator>> (int& val), it immediately stores the "accumulated" 0 in your int variable. Example:
#include <iostream>
int main (const int argc, const char * const argv[]) {
int b = 100;
std::cout << b << std::endl;
std::cin >> b;
std::cout << b << std::endl;
return 0;
}
Execution:
100
b
0
As for the cast, when you cast the value 'b' to an integer, you already have a byte in memory with the value 98, which you then print as an integer. When you use >> the resulting value in memory is 0, which you then print as an integer.
The input operation that you are trying to do is failing. Since a is an int cin expects an int. since it gets a char it fails. You can test this by changing you code to:
int a;
cin>>a;
if(!cin)
cout << "input failed";
else
cout<<a<<endl;
Input:
a
Output:
input failed
See this live example
When you are using 'b' to cin a integer value, your program think you are input a invalid number, so it does't assign value by int('b'). still using initial value of a
not sure if this what you're finding:
char a;
cin >> a;
cout << a << endl;
try to change int to char,
when you enter 3, it'll output 3;
when you enter b, it'll output b;
if you want to output ascii, you can make cout like:
cout << (int) a << endl;
then you'll get 98 when you enter b
If extraction fails (e.g. if a letter was entered where a digit is
expected), value is left unmodified and failbit is set. (until C++11)
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, std::numeric_limits::max() or std::numeric_limits::min()
is written and failbit flag is set. (since C++11)
from https://en.cppreference.com/w/cpp/io/basic_istream/operator_gtgt