0

I am trying to copy a string into string variable "cpy" via a string pointer "seq" , my stub code -

#include <iostream>
#include<string.h>

using namespace std;
int main(){
string *seq[5],str[5],cpy;

for(int i=4;i>=0;i--)
{
cin>>str[i];
seq[i]=&str[i];
}

for(int i=0;i<5;i++)
{
//copy *seq[i] to cpy so that cout gives string str[i]; 
cout<<cpy<<endl; // print all strings according to new order
}
}

how do I accomplish this task?

  • You should use `` for `std::string` and not `` – Killzone Kid May 27 '18 at 14:34
  • The pointer should only point the first place and then you should promote 'i' and not point each cell in the array. – Nir.Hayun May 27 '18 at 14:36
  • I am trying to copy a string into string variable "cpy" via a string pointer "seq" , ??? Can you make your question a bit clearer , You are taking array of string pointer and as per your example code is not correct with string.h as @KillzoneKid also mentioned. Can you write more here , You want to copy a string or array of string pointers. – ATul Singh May 27 '18 at 14:36
  • seq points to an array & I want to copy this array(to which seq[i] points) into string variable- cpy –  May 27 '18 at 14:59

2 Answers2

0

You may use the + operator to concatenatestrings:

for(int i=0;i<5;i++)
{
    cpy += *seq[i];
}
cout<<cpy<<endl; // print all strings according to new order

However, I don't see in your code where you initialize seq, which seems to be a pointer - for your example I would recommend to just omit the *.

Philipp Ludwig
  • 3,758
  • 3
  • 30
  • 48
  • I don't wish to store an extra copy of string ,that's why I'm using pointers to just point to strings –  May 27 '18 at 15:04
  • My bad, I see that you are storing a pointer. Note however that you can also use references, e.g. ``string& ref = some_string``. References have some advantages which are discussed in high detail in this question: https://stackoverflow.com/questions/57483/what-are-the-differences-between-a-pointer-variable-and-a-reference-variable-in – Philipp Ludwig May 27 '18 at 15:15
0

I used library string:

#include<string>

Then you can do what you need:

#include <iostream>
#include<string>

using namespace std;
int main(){
 string *seq[5],str[5],cpy="";//you must assign empty string for cpy

 for(int i=4;i>=0;i--)
 {
  cin>>str[i];
  seq[i]=&str[i];
 }

 for(int i=0;i<5;i++)
 {
  cpy += *seq[i];
  cout<<cpy<<endl; // print all strings according to new order
 }
 return 0;
}
TaQuangTu
  • 2,155
  • 2
  • 16
  • 30
  • 1
    `//you must assign empty string for cpy` No you don't, not with `std::string` anyway. It will be default initialized to "". – Killzone Kid May 27 '18 at 14:39
  • thanks I also added cpy.clear() at end of for loop to prevent concatenation –  May 27 '18 at 15:02
  • if you dont want concatenation, you can do as the answer for your post of @Philipp Ludwig – TaQuangTu May 27 '18 at 15:07