Pressing return key to skip to next!

I was making this program where I had to take inputs in an array. And I wanted some places in the array to not be filled. That I press the return key and the program skips array[6], leaves it empty and moves to the next index array[7].
What type are the elements in the array? Numbers, strings?
Numbers!
I guess you use operator>> to read the input from std::cin, something like this:
 
std::cin >> array[i];

Problem is that operator>> ignores all whitespace characters at the start so it will wait for more input as long as you enter spaces and newlines...

One way you could solve this is to use std::getline to read the line as a string and use std::istringstream to read the number.
1
2
3
4
5
6
7
8
9
10
11
12
13
std::string line;
std::getline(std::cin, line);
std::istringstream iss(line);
int num;
if (iss >> num)
{
	array[i] = num;
}
else
{
	// Not sure what you mean by leaving array[i] empty
	// but here is where you should do it.
}

The else part will run if the line is empty or for some other reason it could not read a number from it. If you want to handle invalid lines and empty lines differently you can easily do that by checking if the string is empty before using std::istringstream.
Last edited on
There's no such thing as an "empty" number.
Force your user to provide a value. (Even if that value is zero.)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>

int main()
{
    const std::size_t N = 10 ;
    int a[N] {} ; // initialize to all zeroes

    std::cout << "at the prompt, type in an integer and then enter "
              << "(or just an immediate enter for zero)\n" ;

    for( int& v : a )
    {
        std::cout << '?' ;
        char c ;
        std::cin.get(c) ;
        if( c != '\n' )
        {
            std::cin.putback(c) ;
            std::cin >> v ;
            std::cin.ignore( 1000, '\n' ) ;
        }
    }
}

Topic archived. No new replies allowed.