Abdul Moiz
Abdul Moiz

Reputation: 3

how to terminate cin taking a value on space intead of carriage return because it cause the program to go to next line and I want it on the same line?

#include <iostream>

int main()
{
    int int1, int2;
    std::cout << "Enter pair of integer e.g (Integer1,integer2)  : ";
    std::cout << "( ";
    std::cin >> int1;
    std::cout << ",";
    std::cin >> int2;
    std::cout << " )\n\n";
}

Actual output: Enter pair of integer e.g(Integer1,integer2) :(1

,2

)

I want to cin both value on same line.

desire output: Enter pair of integer e.g(Integer1,integer2) :(1,2)

Upvotes: 0

Views: 44

Answers (1)

sweenish
sweenish

Reputation: 5192

#include <iostream>

int main()
{
    int int1, int2;
    std::cout << "Enter pair of integer e.g (Integer1,integer2)  : ";
    std::cin >> int1 >> int2;

}

If you type two numbers without a space, you will get their values. You lose the "()", but do you really need them?

Here's an example where the user is required to type the pair in themselves. It's a bit flexible as they can type it in almost any way they choose. The only requirement is that there is a comma separating the numbers. It's missing a lot of validation that I would consider mandatory for this approach. Like determining if there are in fact numbers entered, the comma restriction is almost arbitrary, so it would need to go away as well. But this is enough code to get started.

#include <iostream>
#include <string>

int find_number(std::string str, int startIdx = 0)
{
    std::string digits("0123456789");
    int numStart = str.find_first_of(digits, startIdx);

    return std::stoi(str.substr(numStart));
}

int main()
{
    std::string numPair;
    std::cout << "Enter pair of integer e.g (Integer1,integer2)  : ";
    std::getline(std::cin, numPair);

    int firstNum = find_number(numPair);
    int commaLoc = numPair.find_first_of(",");
    int secondNum = find_number(numPair, commaLoc);

    std::cout << firstNum << '\n' << secondNum << '\n';
}

Per the question in your headline, std::cin stops on all whitespace, not just hitting the enter key. But you always have to hit Enter when you're finished with your input.

Upvotes: 1

Related Questions