Look at the following array definition. char str[10]; Assume that name is also a char array, and it holds a C-string. Write code that copies the contents of name to str if the C-string in name is not to big to fit in str.

Respuesta :

Answer:

if(strlen(name)<=9)

  strcpy(str,name);        

 

Explanation:

In the above chunk of code, IF condition is used which checks if the length of the array name is less than or equals to 9.

This means that in order to copy the contents of name array to str array the string contained in name should not be larger than the length of the str. The length of str is given which is 10.

So strlen() function returns the length of the string in the name array and if this length is less than or equal to 9 then the If condition evaluates to true and the next line strcpy(str,name); is executed which copies the contents of name array to the str array.

strcpy() function is used to copy the string contents from source to destination. Here the source is the name array and the destination is str array.

If you want to see the output then you can enter some contents into the name array as follows:

#include <iostream>

#include <string.h>

using namespace std;

int main()

{

  char str[10];

  char name[]={'a','b','c','d','e','f','g','h','i'};

  if(strlen(name) <= 9)

  strcpy(str,name);

  cout<<str;

   }

This program has two array str of length 10 and name[] array contains 9 characters. These contents are copied to the str array if the length of the name array is less than or equal to 9, which is true, so the ouput is:

abcdefghi

Ver imagen mahamnasir