How store integers given in a line in diferent variables? [duplicate] - c++

I have looked to no avail, and I'm afraid that it might be such a simple question that nobody dares ask it.
Can one input multiple things from standard input in one line? I mean this:
float a, b;
char c;
// It is safe to assume a, b, c will be in float, float, char form?
cin >> a >> b >> c;

Yes, you can input multiple items from cin, using exactly the syntax you describe. The result is essentially identical to:
cin >> a;
cin >> b;
cin >> c;
This is due to a technique called "operator chaining".
Each call to operator>>(istream&, T) (where T is some arbitrary type) returns a reference to its first argument. So cin >> a returns cin, which can be used as (cin>>a)>>b and so forth.
Note that each call to operator>>(istream&, T) first consumes all whitespace characters, then as many characters as is required to satisfy the input operation, up to (but not including) the first next whitespace character, invalid character, or EOF.

Yes, you can.
From cplusplus.com:
Because these functions are operator overloading functions, the usual way in which they are called is:
strm >> variable;
Where strm is the identifier of a istream object and variable is an object of any type supported as right parameter. It is also possible to call a succession of extraction operations as:
strm >> variable1 >> variable2 >> variable3; //...
which is the same as performing successive extractions from the same object strm.
Just replace strm with cin.

Related

Return value of (std::cin >> variable)

I am a C++ beginner,
#include <iostream>
int main()
{
char v1;
// valid no warning
std::cout << (std::cin >> v1) << std::endl; // return value of the expression expected
return 0;
}
// output: 1
// return value of the expression is 1?
Is the return value of (std::cin >> v1) really 1? Why?
I don't know of a current compiler that will accept your code as it stands right now. g++, clang and Microsoft all reject it, saying they can't find an overload to match the arguments (i.e., an operator<< for ostream that takes an istream as an operand).
It's possible to get the result you've posited with code on this order: std::cout << !!(std::cin >> v1) << "\n";. Depending on the age of the compiler and standard with which it complies, this does one of two things.
With a reasonably current compiler, this will use the Boolean conversion on the istream to get it to match the ! operator, then apply that (twice) to the result, so you write out the result of that operator.
With old enough compilers, there won't be a Boolean conversion operator, but there will be an overload of operator!, which also does a conversion to Boolean (but negated in sense, of course). The result of that will then be negated by the second !.
Either way, you end up writing out a Boolean value (or int containing zero or one on an old enough compiler) that indicates whether the stream is in a failed or successful state.
This is done to allow you to check input as you're reading it, so you can process input data sanely. For example, when/if you want to read all the values in a file, stopping at the end of the file, or when you encounter something that can't be interpreted as the desired type, you can write code on this general order:
// read integers from a file and print out their sum
int temp;
int total = 0;
while (std::cin >> temp) {
total += temp;
}
std::cout << total << "\n";
The while loop uses the conversion to Boolean to determine whether an attempt at reading a value was successful or not, so it continues reading values as long as that happens successfully, and quits immediately when reading is unsuccessful.
One common source of errors is to write a loop on this order instead:
while (std::cin.good()) { // or almost equivalently, check for end of file.
std::cin >> temp;
total += temp;
}
But loops like this get the sequence incorrect. One common symptom of the problem with this is that the last number in the file will be added to the total twice instead of once.
std::cin >> v1 returns cin; Not sure what type it gets converted to for std::cout, but most likely it indicates the state of cin, where 1 is good
Is the return value of (std::cin >> v1) really 1
No, see the ref for cin, it will return a istream.
Your codes will not work, we can not pass ::istream (std::cin) to operator<< of a std::ostream (std::cout).
Shoule be like the following:
char v1;
cout << "Input a char:";
cin >> v1;
The program only works for Pre-C++11 because the conversion to bool is not explicit.
Starting from C++11, the program will no longer work because the conversion to bool is explicit.
Note that std::cin >> v1; returns std::cin and not 1. But there is no operator<< for std::ostream that takes a std::cin.
The reason it works for Pre-C++11 is because in this case the conversion to bool was not explicit. But starting from C++11, the conversion to bool was made explicit and so the code no longer compiles.
For example,
bool b = std::cin; //WORKS for Pre-C++11 but FAILS for C++11 & onwards
bool b{std::cin}; //OK, WORKS for all versions(Pre-C++11 as well as C++11 & onwards) because in direct initialization we can use explicit conversion

How does this right shifts work: stringstream >> unsigned int >> unsigned int?

Im working with the book SFML Game Development by Examples and I dont really get what this sentence does. I've never seen something like this
void Anim_Directional::ReadIn(std::stringstream& l_stream){
l_stream >> m_frameStart >> m_frameEnd >> m_frameRow
>> m_frameTime >> m_frameActionStart >> m_frameActionEnd;
}
In C++ they got the "bright" idea of overloading the rightshift and leftshift operators with streams to represent serialization/deserialization.
stream >> var
means "read var from stream".
Symmetrically
stream << var
mean "put var into stream"
The operation of "streaming" in or out also returns the stream, so you can chain operations like:
stream >> var1 >> var2;
Note that the "streaming" was chosen just because of the look and because the priority was considered reasonable, but it's still just an overloaded operator and implies for example no strict sequence of evaluation. For example in:
stream << f() << g();
may be function g is called (somewhat surprisingly) before function f.
NOTE: the sequencing problem was handled by hammering this special case in last C++ standard (C++17). While it doesn't hold in general it's guaranteed for shift operators (presumably for this specific reason). So in f()+g() may be f is called later than g, but in f()<<g() this cannot happen.
C++ allows you to overload >> and << operators. std::stringstream is a derivative of std::istream and it inherits the >> operator overloads of std::istream.
The std::istream has a bunch of overloads for many common types. You can find a list of them here.
A typical std::istream >> operator overload looks as follows:
std::istream& operator>>(std::istream& stream, YourType& var) {
/*
** code here to parse and read a 'YourType' into 'var'
*/
/* var is set */
return stream; /* return the same stream to allow chaining */
}
When you do some_stream >> YourType_object, the matching >> operator overload is invoked. In the aforementioned case, our operator overload is invoked with stream parameter taking some_stream and var taking YourType_object.
The >> overloads (and << overloads too) intelligently return the stream which they operated; thereby, allowing a series of >> operators to be chained.

C++ String parse of white spaces [duplicate]

When should std::cin.getline() be used? What does it differ from std::cin?
Let's take std::cin.getline() apart. First, there's std::. This is the namespace in which the standard library lives. It has hundreds of types, functions and objects.
std::cin is such an object. It's the standard character input object, defined in <iostream>. It has some methods of its own, but you can also use it with many free functions. Most of these methods and functions are ways to get one or more characters from the standard input.
Finally, .getline() is one such method of std::cin (and other similar objects). You tell it how many characters it should get from the object on its left side (std::cin here), and where to put those characters. The precise number of characters can vary: .getline() will stop in three cases:
1. The end of a line is reached
2. There are no characters left in the input (doesn't happen normally on std::cin as you can keep typing)
3. The maximum number of characters is read.
There are other methods and functions that can be used with the std::cin object, e.g.
std::string s;
int i;
std::cin >> s; // Read a single word from std::cin
std::cin >> i; // Read a single number from std::cin
std::getline(std::cin, s); // Read an entire line (up to \n) from std::cin
std::cin.ignore(100); // Ignore the next 100 characters of std::cin
In case with char*, std::cin.getline getting line, instead of std::cin getting first word.
Did you read any documentation (e.g. http://www.cplusplus.com/reference/string/getline/)?
Basically, std::cin (or more generally, any std::istream) is used directly in order to obtain formatted input, e.g. int x; std::cin >> x;. std::cin.getline() is used simply to fill a raw char * buffer.
(Very simplefied)My answer is, that std :: cin.getline() can contain spaces, while std :: cin >> can not.
As already others have answered (even better) roughly speaking, use getline() to read an entire line (i.e., a string terminating with \n) and cin>>var to read a number compatible with the type of var (integer, float, double etc.) or a single word.
In this answer I want to emphasize a problem that arises when mixing the two methods. When you do:
int a;
string s;
cin>>a;
getline(cin, s)
cin leaves an end of line, \n, character which is then read by getline();. It is possible to overcome this problem by using cin.ignore().
int a;
string s;
cin>>a;
cin.ignore();
getline(cin, s)

Multiple inputs on one line

I have looked to no avail, and I'm afraid that it might be such a simple question that nobody dares ask it.
Can one input multiple things from standard input in one line? I mean this:
float a, b;
char c;
// It is safe to assume a, b, c will be in float, float, char form?
cin >> a >> b >> c;
Yes, you can input multiple items from cin, using exactly the syntax you describe. The result is essentially identical to:
cin >> a;
cin >> b;
cin >> c;
This is due to a technique called "operator chaining".
Each call to operator>>(istream&, T) (where T is some arbitrary type) returns a reference to its first argument. So cin >> a returns cin, which can be used as (cin>>a)>>b and so forth.
Note that each call to operator>>(istream&, T) first consumes all whitespace characters, then as many characters as is required to satisfy the input operation, up to (but not including) the first next whitespace character, invalid character, or EOF.
Yes, you can.
From cplusplus.com:
Because these functions are operator overloading functions, the usual way in which they are called is:
strm >> variable;
Where strm is the identifier of a istream object and variable is an object of any type supported as right parameter. It is also possible to call a succession of extraction operations as:
strm >> variable1 >> variable2 >> variable3; //...
which is the same as performing successive extractions from the same object strm.
Just replace strm with cin.

std::cin.getline( ) vs. std::cin

When should std::cin.getline() be used? What does it differ from std::cin?
Let's take std::cin.getline() apart. First, there's std::. This is the namespace in which the standard library lives. It has hundreds of types, functions and objects.
std::cin is such an object. It's the standard character input object, defined in <iostream>. It has some methods of its own, but you can also use it with many free functions. Most of these methods and functions are ways to get one or more characters from the standard input.
Finally, .getline() is one such method of std::cin (and other similar objects). You tell it how many characters it should get from the object on its left side (std::cin here), and where to put those characters. The precise number of characters can vary: .getline() will stop in three cases:
1. The end of a line is reached
2. There are no characters left in the input (doesn't happen normally on std::cin as you can keep typing)
3. The maximum number of characters is read.
There are other methods and functions that can be used with the std::cin object, e.g.
std::string s;
int i;
std::cin >> s; // Read a single word from std::cin
std::cin >> i; // Read a single number from std::cin
std::getline(std::cin, s); // Read an entire line (up to \n) from std::cin
std::cin.ignore(100); // Ignore the next 100 characters of std::cin
In case with char*, std::cin.getline getting line, instead of std::cin getting first word.
Did you read any documentation (e.g. http://www.cplusplus.com/reference/string/getline/)?
Basically, std::cin (or more generally, any std::istream) is used directly in order to obtain formatted input, e.g. int x; std::cin >> x;. std::cin.getline() is used simply to fill a raw char * buffer.
(Very simplefied)My answer is, that std :: cin.getline() can contain spaces, while std :: cin >> can not.
As already others have answered (even better) roughly speaking, use getline() to read an entire line (i.e., a string terminating with \n) and cin>>var to read a number compatible with the type of var (integer, float, double etc.) or a single word.
In this answer I want to emphasize a problem that arises when mixing the two methods. When you do:
int a;
string s;
cin>>a;
getline(cin, s)
cin leaves an end of line, \n, character which is then read by getline();. It is possible to overcome this problem by using cin.ignore().
int a;
string s;
cin>>a;
cin.ignore();
getline(cin, s)