【问题标题】:Is there a way to perform arithmetic on integer which has been converted from a string cpp有没有办法对从字符串 cpp 转换的整数执行算术运算
【发布时间】:2021-06-15 13:08:24
【问题描述】:

所以基本上我得到两个坐标形式的字符串输入(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;
}

【问题讨论】:

标签: c++ string integer


【解决方案1】:

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

int x = stoi(x1);

【讨论】:

  • 是的,但我无法使用 std stoi 添加
  • 如上所述,使用stoistring 变量转换为int 变量后,您可以对生成的ints 执行任何算术运算,包括加法、减法等想要...
  • 是的,是的,对不起,我是个白痴,它的工作原理。
  • 我忘了添加sstream头文件
猜你喜欢
  • 1970-01-01
  • 2017-01-10
  • 2013-09-06
  • 1970-01-01
  • 1970-01-01
  • 2013-02-19
  • 1970-01-01
  • 2019-03-24
相关资源
最近更新 更多