所以基本上我以坐标的形式获得两个字符串输入(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
s 放入int
变量并进行算术运算:
int x = stoi(x1);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句