Question

I am using three strings and then putting them together in one string using only for loop...

This is the code:

#include<iostream.h>
#include<conio.h>

int main()
{
  int i,j,k;
  char fn[10]={"Ryan"};
  char sn[10]={"Mclaren"};
  char ln[10]={"Harris"};
  char name[30];
  puts(fn); puts(sn); puts(ln);

  for(i=0;fn!='\0';i++)
  name[i]=fn[i];
  puts(name);

  for(j=0;sn!='\0';j++)
  name[i+j+1]=sn[j];
  name[i+j+1]=' ';

  for(k=0;ln!='\0';k++)
  name[i+j+k+2]=ln[k];
  name[i+j+k+2]='\0';

  printf("\n%s",name);
  getch();
  return 0;   
}

Now this is not giving any output, there are no compilation errors. This is the output:

Ryan
Mclaren
Harris

This is the output of the puts functions. Why is the copying expression not working/displaying?

Was it helpful?

Solution

The conditional in your for loops looks wrong to me, shouldn't you be checking for a terminating zero at the current index position rather than the whole thing?

Something like:

  for(i=0;fn[i]!='\0';i++)
    name[i]=fn[i];
  puts(name);

  for(j=0;sn[j]!='\0';j++)
    name[i+j+1]=sn[j];
  name[i+j+1]=' ';

  for(k=0;ln[k]!='\0';k++)
    name[i+j+k+2]=ln[k];
  name[i+j+k+2]='\0';
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top