有没有办法对从字符串cpp转换而来的整数执行算术运算

Is there a way to perform arithmetic on integer which has been converted from a string cpp

所以基本上我得到两个坐标形式的字符串输入(x,y),然后我将输入字符串(p1 和 p2)中的数字添加到不同的变量,然后添加这些变量(它们是 x1、x2、y1、y2)。那么有没有办法将变量加在一起,即对变量执行算术运算,(不是连接)

#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;
}

您可以使用 std::stoi() 执行此操作。添加一行将这些 string 放入 int 变量并进行计算:

int x = stoi(x1);