anonymous38653
anonymous38653

Reputation: 403

how to ignore n integers from input

I am trying to read the last integer from an input such as-

100 121 13 ... 7 11 81

I can input integer by integer using a loop and do nothing with them. Is there a better way?

Upvotes: 3

Views: 1015

Answers (3)

A M
A M

Reputation: 15265

It all depends on the use case that you have.

Reading a none specified number of integers from std::cin is not as easy at it may seem. Because, in contrast to reading from a file, you will not have an EOF condition. If you would read from a file stream, then it would be very simple.

int value{};
while (fileStream >> value)
    ;

If you are using std::cin you could try pressing CTRL-D or CTRL-Z or whatever works on your terminal to produce an EOF (End Of File) condition. But usually the approach is to use std::getline to read a complete line until the user presses enter, then put this line into a std::istringstream and extract from there.

Insofar, one answer given below is not that good.

So, next solution:

std::string line{};
std::getline(std::cin, line);
std::istringstream iss{line};
int value{};
while (iss >> value)
    ;

You were asking

Is there a better way?

That also depends a little. If you are just reading some integers, then please go with above approach. If you would have many many values, then you would maybe waste time by unnecessarily converting many substrings to integers and loose time.

Then, it would be better, to first read the complete string, then use rfind to find the last space in the string and use std::stoi to convert the last substring to an integer.

Caveat: In this case you must be sure (or check with more lines of code) that there are no white space at the end and the last substring is really a number. That is a lot of string/character fiddling, which can most probably avoided.

So, I would recommend the getline-stringstream approach.

Upvotes: 2

Rohan Bari
Rohan Bari

Reputation: 7736

You can try this simple solution for dynamically ignoring rest of the values except the last given in this problem as shown:

int count = 0;
int values, lastValue; // lastValue used for future use

std::cout << "Enter your input: ";

while (std::cin >> values) {
    lastValue = values; // must be used, otherwise values = 0 when loop ends
    count++;
}

std::cout << lastValue; // prints

Note: A character must be required to stop the while(), hence it's better put a . at last.

Output example

Enter your input: 3 2 4 5 6 7.
7

Upvotes: 1

lenik
lenik

Reputation: 23556

Try this:

for( int i=0; i<nums_to_ignore; i++) {
    int ignored;
    std::cin >> ignored;
}

Upvotes: 0

Related Questions