简体   繁体   中英

c++ c-strings, strncat, strncpy

This program is supposed to input someones name and output it like " Last, first middle". The names are supposed to be stored in 3 different arrays and their is a fourth array for the full name at the end. I am also supposed to use strncpy and strncat to build the fourth array. My issue im having is i dont know what the use of strncpy would be in this situation and how to use it. I can make the program say "first middle last" but not the correct output. Another issue im having is the while loop is supposed to allow the user to say 'q' or 'Q' and quit the program but it doesnt do this

#include <iomanip>
#include <iostream>
#include <cctype>
using namespace std; 

int main()
{
char replay; //To hold Q for quit

const int SIZE = 51;
char firstName[SIZE]; // To hole first name
char middleName[SIZE]; // To hold middle name
char lastName[SIZE]; // To hold last name
char fullName[SIZE]; //To hold the full name
int count = 0;
int maxChars1;
int maxChars2;



cout << "Enter Q to quit or enter your first name of no more than " << (SIZE - 1)
     << " letters: ";
cin.getline(firstName, SIZE);

while(firstName[SIZE] != 'Q' || firstName[SIZE] != 'q')
{
cout << "\nEnter your middle name of no more than " << (SIZE - 1)
     << " letters: ";
cin.getline(middleName, SIZE);

cout << "\nEnter your last name of no more than " << (SIZE - 1)
     << " letters: ";
cin.getline(lastName, SIZE);

maxChars1 = sizeof(firstName) - (strlen(firstName) + 1);
strncat(firstName, middleName, maxChars1);

cout << firstName << endl;

maxChars2 = sizeof(lastName) - 1;
strncpy(firstName, lastName, maxChars2);
lastName[maxChars2] = '\0';

cout << lastName << endl;
    }

system("pause");
return 0;
}

Your while loop doesn't work because of several reasons:

  • You're actually looking one past the end of the firstName array ( firstName[SIZE] ) rather than the first character ( firstName[0] ).
  • You're not checking to make sure firstName is only a single character q or Q .
  • You're only asking for the first name one time, before the loop, instead of every loop.

Your call to strncpy doesn't look right. As written, you're taking the last name and copying it to firstName , destroying the first and middle names that you just concatenated together there. Like @steve-jessop said, assemble the full name in fullName .

You're probably supposed to use strncpy and strncat because this is a contrived example/exercise where the buffer taking the full name is of a restricted size, so some name combinations will not fit, and need to be truncated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM