Reputation: 29
So basically I am getting two string inputs in the form of coordinates as (x,y) and then I am adding the numbers from the inputted string (which are p1 and p2) to different variables and then adding those variables (which are x1,x2,y1,y2). So is there a way to add the variables together i.e perform arithmetic on the variables, (not concatenate)
#include <iostream>
#include <conio.h>
#include<math.h>
#include<string>
using namespace std;
int main() {
string p1, p2;
cout << "Input x and y cordinates of first point, as (x,y): " << endl;
cin >> p1;
string x1, x2, y1, y2;
for (int i = 0; i < p1.length(); i++) {
if (p1[i] == ',') {
for (int j = 1; j < i; j++) {
x1 += p1[j];
cout << p1[j];
}
cout << endl;
for (int k = i + 1; k < (p1.length()-1); k++) {
y1 += p1[k];
cout << p1[k];
}
}
}
cout << "Input x and y cordinates of second point, as (x,y): " << endl;
cin >> p2;
for (int i = 0; i < p2.length(); i++) {
if (p2[i] == ',') {
for (int j = 1; j < i; j++) {
x2 += p2[j];
cout << p2[j];
}
cout << endl;
for (int k = i + 1; k < (p2.length() - 1); k++) {
y2 += p2[k];
cout << p2[k];
}
}
}
cout << "Adding x1 and x2 gives: " << x1+x2;
court << "Adding y1 and y2 gives: << y1+y2 << endl;
}
Upvotes: 2
Views: 82
Reputation: 2265
You can do this with std::stoi()
. Add a line to put these string
s into int
variables and do your arithmetic:
int x = stoi(x1);
Upvotes: 2