0

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++?

Pat. ANDRIA
  • 2,330
  • 1
  • 13
  • 27
Jegors Čemisovs
  • 608
  • 6
  • 14
  • https://stackoverflow.com/questions/2006161/changing-the-value-of-const-variable-in-c Please check here, I think this question is duplicate. – Filip Feb 18 '21 at 11:58
  • IILE? `auto const number = [](){int x; cin >> x; return x;}();`? – EOF Feb 18 '21 at 12:03

4 Answers4

7

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.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
1

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.

Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93
-1

You can do this with constructing a temporary "istream_iterator". Example:

const int number = *istream_iterator<int>(cin);
kfc
  • 567
  • 1
  • 5
  • 10
  • is it always safe to dereference the iterator? – 463035818_is_not_an_ai Feb 18 '21 at 12:09
  • @largest_prime_is_463035818 not if cin was closed. – spectras Feb 18 '21 at 12:11
  • @spectras Is the behavior undefined then or are you guaranteed an exception? If the behavior is undefined, is there something like an `.at(0)` member function that guarantees an exception? – EOF Feb 18 '21 at 12:13
  • 2
    @EOF From cppreference: *“When a valid std::istream_iterator reaches the end of the underlying stream, it becomes equal to the end-of-stream iterator. Dereferencing or incrementing it further invokes undefined behavior.”* – spectras Feb 18 '21 at 12:16
-4

Try this instead:

//Declare int variable
int number;

//Read variable
cin >> number;
I'm Weverton
  • 562
  • 4
  • 5