How to properly re-write this code from Java to C++:
final int number = scanner.nextInt();
I’m trying const number << cin; but it doesn’t work.
The number should be constant.
Is it possible in C++?
How to properly re-write this code from Java to C++:
final int number = scanner.nextInt();
I’m trying const number << cin; but it doesn’t work.
The number should be constant.
Is it possible in C++?
You cannot assign to a const. You must initialize it:
int x = 0;
std::cin >> x;
const int number = x;
If you like, put it inside a function, so you can write:
const int number = read_number();
As mentioned in comments, with a immediately invoked lambda expression you can do that all in one line:
const int number = [](){ int x; std::cin >> x; return x; }();
The lambda expression is [](){ int x; std::cin >> x; return x; } and () immediately calls it and number is initialized with the returned value.
There is something called istream_iterator. This class lets you to iterate over a stream as if it were a container. Here is how you use it:
#include <iostream>
#include <iterator>
int main() {
std::istream_iterator<int> it{ std::cin }, end{};
// Must test against end
const int n1 = it == end ? 0 : *it++;
const int n2 = it == end ? 0 : *it++;
}
This assigns a default 0 if the stream fails. You could do the error handling other ways too. This is particularly useful for making the variable const, and the iterator can be used as many times as you like. You can use it to initialize containers like std::vector:
std::vector<int> vec{ it, end };
This will read all integers until the stream fails, end of file, etc.
You can do this with constructing a temporary "istream_iterator". Example:
const int number = *istream_iterator<int>(cin);
Try this instead:
//Declare int variable
int number;
//Read variable
cin >> number;