在c ++中连接变量

时间:2018-03-09 22:40:03

标签: c++ concatenation sstream

我的问题是这样的: 假设我有3个变量(i = 1,j = 2,k = 3) 我想这样做:“a = 0.ijk”所以a == 0.123 但是这些变量是多个的,所以我将它们的值保存在数组上。

我尝试使用sstream将它们从字符串转换为int(123)然后我将它除以1000得到0.123但是它不起作用...

float arrayValores[ maxValores ];

ostringstream arrayOss[ maxValores ];

...

arrayOss[indice] << i << j << k;

                istringstream iss(arrayOss[indice].str());

                iss >> arrayValores[indice];

                arrayValores[indice] = ((arrayValores[indice])/1000)*(pow(10,z)) ;

                cout << arrayValores[indice] << "  ";

                indice++;

有人能帮助我吗?

2 个答案:

答案 0 :(得分:1)

我对你的要求感到困惑,但这是你想要做的吗?

#include <iostream>
#include <string>

using namespace std;

int main() 
{
    int i = 1;
    int j = 2;
    int k = 3;

// Create a string of 0.123
    string numAsString = "0." + to_string(i) + to_string(j) + to_string(k);
    cout << numAsString << '\n';

// Turn the string into a floating point number 0.123
    double numAsDouble = stod(numAsString);
    cout << numAsDouble << '\n';

// Multiply by 1000 to get 123.0
    numAsDouble *= 1000.0;
    cout << numAsDouble << '\n';

// Turn the floating point number into an int 123
    int numAsInt = numAsDouble;
    cout << numAsInt << '\n';

    return 0;
}

答案 1 :(得分:0)

这是你想要达到的目标吗?

#include <iostream>
#include <string>
#include <cmath>
#include <vector>

int main() {
    // your i, j, k variables
    std::vector<int> v = {1, 2, 3};
    double d = 0;
    for (int i = 0; i < v.size(); i++) {
        // sum of successive powers: 1x10^-1 + 2x10^-2 + ...
        d += pow(10, -(i + 1)) * v[i];
    }
    std::cout << d << "\n";
}