#Is there any faster(with less code lines required) way to swap the structures here?

8 messages · Page 1 of 1 (latest)

thick pond
#
#include<iostream>
using namespace std;

int main()
{
    //declaration and initialization 
    struct
        {
        char name[30];
        int val=20;
        } a;
    struct
        {
        char name[30];
        int val=50;
        } b;
    struct
        {
        char name[30];
        int val;
        } temp;
    strcpy(a.name,"Twenty"); 
    strcpy(b.name,"Fifty");
    
    //ourput before swapping 
    cout<<a.val<<" "<<a.name<<"\n";
    cout<<b.val<<" "<<b.name<<"\n";
    cout<<"press ENTER to swap\n";
    getchar();
    
    //swapping process
    strcpy(temp.name,a.name);
    temp.val=a.val;
    
    strcpy(a.name,b.name);
    a.val=b.val;
    
    strcpy(b.name,temp.name);
    b.val=temp.val;
    
    //output after swapping
    system("clear");
    cout<<"After swapping\n";
    cout<<a.val<<" "<<a.name<<"\n";
    cout<<b.val<<" "<<b.name<<"\n";

    return 0;
}
ripe tulipBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question run !howto ask.

coarse bison
#

Your structs are static, no pointers or so, so a memcpy will do: ```c++
memcpy(&temp, &a, sizeof(a));
memcpy(&a, &b, sizeof(b));
memcpy(&b, &temp, sizeof(temp));

ripe tulipBOT
#

#include <iostream>
using namespace std;

int main() {
  // declaration and initialization
  struct {
    char name[30];
    int val = 20;
  } a;
  struct {
    char name[30];
    int val = 50;
  } b;
  struct {
    char name[30];
    int val;
  } temp;
  strcpy(a.name, "Twenty");
  strcpy(b.name, "Fifty");

  // ourput before swapping
  cout << a.val << " " << a.name << "\n";
  cout << b.val << " " << b.name << "\n";
  cout << "press ENTER to swap\n";
  getchar();

  // swapping process
  strcpy(temp.name, a.name);
  temp.val = a.val;

  strcpy(a.name, b.name);
  a.val = b.val;

  strcpy(b.name, temp.name);
  b.val = temp.val;

  // output after swapping
  system("clear");
  cout << "After swapping\n";
  cout << a.val << " " << a.name << "\n";
  cout << b.val << " " << b.name << "\n";

  return 0;
}

ProNub
silk pagoda
#

@thick pond
First of all declare your struct once and outside main instead of three times for each variable.
Second, just use std::swap. No temp needed.

thick pond
#

Great. Thanks guys

#

!solved