get numbers from one line

done thx
Last edited on
numbers are separate by a space . You can either write multiple instruction cin ; So you would have to press enter at each entry of integer , or you can use cin >> >> >> ; A single intruction , by you would have to enter all integers separated by a space before pressing Enter . Think of each cin is waiting for an Enter before assigning values . So it really depends.
You can either write multiple instruction cin ; So you would have to press enter at each entry of integer , or you can use cin >> >> >> ; A single intruction , by you would have to enter all integers separated by a space before pressing Enter
This is completely wrong. There is no difference between cin>>x>>y and cin>>x; cin>>y; at all. Both values can be entered by pressing enter after each or on single line in all cases.

Formatted input is separated by not spaces, but whitespace characters. It does not matter if it is space, newline or tab: they are all threated the same by isspace() and whitespace skipper (std::ws).

Input in most terminals is line buffered, so it does not send to your program until you press enter. Bt you can potentially write all input that your program will need, press enter and enjoy all output without meddlesome input pauses. As long as you do not do something stupid as clearing whole input buffer in your program.
> lets say the task is , user have to enter 2 numbers in the same line between those numbers must be a space ,
> and then it will write first number is : , and second number is : help pls

One option is to read the entire line into a string with std::getline() and then parse the string

The other is to parse the input directly:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
 include <iostream>
#include <cctype>

int main()
{
    std::cout << "please type in the first number, a single space, the second number "
                 "and immediately hit returm\n" ;

    int first ;
    int second ;
    char space ;

    if( std::cin >> first && // the first number
        std::cin.get(space) && space == ' ' && // followed by a space
        !std::isspace( std::cin.peek() ) && // not more than one space
        std::cin >> second && // then the second number,
        std::cin.peek() == '\n' )  // immediately followed by new line
    {
        std::cout << " first number is: " << first << '\n' ;
        std::cout << "second number is: " << second << '\n' ;
    }

    else std::cout << "badly formed input\n" ;
}
Topic archived. No new replies allowed.