This program is suppose to do 3 things:
1 - copy a string using: strncpy (without Null) and strncpy (with null)
2- Input a string and reverse it (i.e. enter First Name Last and output Last, First)
3- Use a substring to that will read a portion of a string
The following is the code I have, but it just doesn't want to work and I can't figure out why.
Any help would be greatly appreciated.
Thank you
Code:
#include<iostream>
using std::cout;
using std::cin;
using std::endl;
using std::flush;
#include <cstring>
using std::string;
void mystrncpy (char *, char *, int);
void LastNameFirst (char *, char *);
void substr (char *, char*, int, int);
const int MAX_STRING = 200;
int main()
{
char Source[MAX_STRING];
char Destination[MAX_STRING];
int MaxLength;
char Name[MAX_STRING];
char NewName[MAX_STRING];
int StartIndex;
int SubMaxLength;
cout <<"Enter string to be copied: ";
cin.getline(Source, MAX_STRING, '\n');
cout <<"Enter number of characters to be copied: ";
cin>>MaxLength;
cout<<"\nThe string you entered is: ";
cout<<Source;
mystrncpy (Destination, Source, MaxLength);
cout<<endl;
cout<<"\nEnter name (in the form First name, Space, Last Name): ";
cin.getline(Name, MAX_STRING, '\n');
for (int i=0; i<3; i++){
LastNameFirst (Name, NewName);
cout<<"Name after conversion is: "<<NewName<<endl;
}
cout<<"\nEnter a string: ";
cin.getline(Source, MAX_STRING, '\n');
cout<<"Enter a starting index number: ";
cin>>StartIndex;
cout<<"Enter a length to copy: ";
cin>>SubMaxLength;
cout<<"\nThe string you entered was: "<<Source;
cout<<"\nThe converted string is: ";
substr (Destination, Source, StartIndex, SubMaxLength);
return 0;
}
void mystrncpy (char *Destination, char *Source, int MaxLength)
{
strncpy(Destination, Source, MaxLength);
cout<<"\nThe string you entered using strncpy is: "<<Destination[MaxLength];
strncpy(Destination, Source, MaxLength-1);
Destination[(MaxLength - 1)] = '\0';
cout<<"\nThe string you entered using mystrncpy is: "<<Destination<<endl;
}
void LastNameFirst (char *Name, char *NewName)
{
char *p;
p = strchr(Name, ' ');
*p = 0;
//copy last name to NewName, append ", " and
//concatenate first name
strcpy(NewName, p+1);
strcat(NewName, ", ");
strcat(NewName, Name);
//replace the NULL char with the original blank
*p = ' ' ;
}
void substr(char *Destination, char *Source, int StartIndex, int SubMaxLength)
{
string (Destination, StartIndex, SubMaxLength);
cout<<Destination[StartIndex, SubMaxLength+1]<<endl;
}