-1

I have question about putting data below in a string array , I mean that is it possible to do as bellow:

for(int i{};i<num;i++)
    string[i]={"The degree of",i,"'th vertice is",degree[i]}

I have tried that and I know its not practical in c++ but is there any other way to do so, my goal is to return a string that number of each degree is saved in by a function called degree,as what I have mentioned (for example "The degree of 4'th vertice is 2") . so is there possible to do so? I want to call the function as below:

std::cout<<degree();

thanks for your attention.

A.R.S.D.
  • 180
  • 3
  • 13
  • 4
    `string[i] = "The degree of " + std::to_string(i) + "'th vertice is " + std::to_string(degree[i]);` – JLev Nov 08 '17 at 11:12
  • thanks for your answer but is there possible to save text below in string and not string array: (The degree of 4'th vertice is 2 (new line) The degree of 5'th vertice is 3 (new line) The degree of 6'th vertice is 0 (new line) The degree of 7'th vertice is 6) – A.R.S.D. Nov 08 '17 at 11:20
  • please provide a [mcve]. You better ask for what you want to do and not for something different ;) You cant print a string array like this `std::cout< – 463035818_is_not_an_ai Nov 08 '17 at 11:25
  • sorry for not expressing my mean correctly I want to store all vertice degrees in one string so when I call the function like this: std::cout< – A.R.S.D. Nov 08 '17 at 11:39

2 Answers2

1

Sure, you can put everything in a single string and put a newline ('\n') between each logical line. Just combine the code snippets given above:

std::string degrees()
{
    std::string   lines;

    for(int i{};i<num;i++)
        lines += "The degree of " + std::to_string(i) +
                 "'th vertice is " + std::to_string(degree[i]) + '\n';

   return lines;
}
Bo Persson
  • 90,663
  • 31
  • 146
  • 203
  • 1
    @A.salehy Then mark it as [accepted answer](https://stackoverflow.com/help/accepted-answer)! This the right way to say thank you in SO. – HMD Nov 08 '17 at 13:08
1

You could try something like this as well (edited to remove argument passing to degrees fnc, as OP doesn't want that):

#include <iostream>
#include <sstream>

std::vector<int> degree = { 1,5,4,8,2,12,4,30,45,22 };

std::string degrees()
{
    std::ostringstream oss;

    for (size_t i = 0; i < degree.size(); ++i)
        oss << (i > 0 ? "\n" : "") << "The degree of " << i + 1 << "'th vertice is " << degree[i];

    return oss.str();
}

int main()
{

    std::cout << degrees() << std::endl;

    return 0;
}

Prints:

enter image description here

Killzone Kid
  • 6,171
  • 3
  • 17
  • 37