String concatenation in C++

Hello,
I have two problems in the below code. (line 20 and line 30)
1. I want to save the name as P0, P1, and P2. but the below code doesn't work.

P[i].Name = "P" + i;


2. display P0, P1 and P2 but just show P
cout << "P" + i;

Thanks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
  #include <iostream>
#include<string>
using namespace std;

struct Process
{
    int Enter; int Duration; string Name;
};

int main()
{   
    int n; cout << "Number of Process: "; cin >> n;
    Process* P = new Process[n] ;
    for (int i = 0; i < n; i++)
    {
        cout << "Enter P" << i << " : ";
        cin >> P[i].Enter;
        cout << "Enter P" << i << " : ";
        cin >> P[i].Duration;
        P[i].Name = "P" + i; // Problem
    }
    int Time = 0;
    cout << "0";
    for (int i = 0; i < n; i++)
    {
        Time += P[i].Duration;
        for (int j = 1; j <= P[i].Duration; j++)
        {
            if (j == (int)P[i].Duration / 2)
                cout << "P" + i; // Problem
            else cout << "__";
        }
        cout << Time;
    }
    return 0;
}
Last edited on
Convert the integer to a string with std::to_string
https://en.cppreference.com/w/cpp/string/basic_string/to_string

1
2
3
4
P[i].name = 'P' + std::to_string(i) ;

std::cout << 'P' + std::to_string(i) ;
// or: std::cout << 'P' << i ; 

Topic archived. No new replies allowed.