Question & Answer: Alter the code below that test it by experiment ing with different limitatyions for the str string. it helps if you replce…..

Alter the code below that test it by experiment ing with different limitatyions for the str string. it helps if you replce the number 600 with the symbolic constant STRMAX, putting the following #define directive at the beginning of the program. During preprocessing, this directive causes the compiler t replace occurrences of STRMAX in the source code with indicated text(600).

#define STRMAX 600

you can then use STRMAX to declare the lenght of str

char str[STRMAX];

and then use STRMAX to determine how many bytes to copy:

strncpy(str, “nMy name is “, STRMAX);

strncat(str, name, STRMAX – strlen(str));

the beauty of this approach is that if you need to change the maximum string size, you need to change only one line of code (the line containing the #define diretive) and then recompile.

#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;



int main() {

    char str[600];
    char name[100];
    char address[200];
    char work[200];

    cout << "Enter name and press ENTER: ";
    cin.getline(name, 100);
    cout << "Enter address and press ENTER: ";
    cin.getline(address, 200);
    cout << "Enter workplace and press ENTER: ";
    cin.getline(work, 200);
    strncpy(str, "nMy name is ",20);
    strcat(str, name);
    strncat(str, ", I live at ",20);
    strncat(str, address, 600 - strlen(str));
    strncat(str, ", nand I work at ",20);
    strcat(str, work);
    strcat(str, ",");

    cout << str << endl;
    return 0;
}

Expert Answer

 /*C++ Program to make use of #define*/

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

#define STRMAX 600 // The macro STRMAX is defined to 600
//using namespace std;

int main() {

char str[STRMAX];
char name[STRMAX];
char address[STRMAX];
char work[STRMAX];

cout << “Enter name and press ENTER: “;
cin.getline(name, STRMAX);
cout << “Enter address and press ENTER: “;
cin.getline(address, STRMAX);
cout << “Enter workplace and press ENTER: “;
cin.getline(work, STRMAX);
strncpy(str, “nMy name is “,STRMAX);
strcat(str, name);
strncat(str, “, I live at “,STRMAX);
strncat(str, address, STRMAX – strlen(str));
strncat(str, “, nand I work at “,STRMAX);
strcat(str, work);
strcat(str, “,”);

cout << str << endl;
return 0;
}

//—————————————

output

Still stressed from student homework?
Get quality assistance from academic writers!