How to separate numbers from a character?

closed account (Ey80oG1T)
Let's say that I have an input that is a pair of coordinate points: x,y. Two numbers, and a comma in between (no space). How would I separate the two numbers into two different integer variables?

For example:

1
2
Input: 12,10
X coordinate is 12 and Y coordinate is 10
Last edited on
1
2
3
4
5
6
7
#include <sstream>

int main() {
    int x, y;
    std::istringstream is("12,10");
    is >> x >> y;
}
closed account (Ey80oG1T)
Is there a way to do it just with standard input and output header?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>

int main ()
{
    int first, last;
    
    std::cout << "Pls enter <first,last>: ";
    
    std::cin >>first;
    std::cin.ignore(256,',');
    std::cin >> last;
    std::cout << "Tada! " << first << ' ' << last << ' ' << first + last << '\n';
    
    return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
#include <string>

using namespace std;

int main()
{
    int x;
    int y;
    
    // user types: 123,10;
    cout << "Input: ";
    {
        string first_num;
        getline(cin, first_num, ',');
		      
        string second_num;
        getline(cin, second_num);
		
        try
        {
            x = stoi(first_num);
            y = stoi(second_num);
        }
        catch (...)
        {
            cout << "Error: Invalid number\n";   
            return 1;
        }
    }

    cout << "x = " << x << ", y = " << y << '\n';
}

Edit: againtry's is nice in that it doesn't require string-to-int parsing.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
using namespace std;

int main()
{
   char comma;
   int x, y;
   cout << "Input X, Y: ";
   cin >> x >> comma >> y;
   cout << "The x coordinate is " << x << " and the y coordinate is " << y << '\n';
}


Input X, Y: 10,12
The x coordinate is 10 and the y coordinate is 12
Topic archived. No new replies allowed.