need help on c++ program please. // SmpCStrings.cpp // Kim Buckner // COSC1030,
ID: 3816314 • Letter: N
Question
need help on c++ program please.
// SmpCStrings.cpp
// Kim Buckner
// COSC1030, Sp 2017
// Lecture 19
// Playing with null-terminated C-strings.
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
#include<cstring>
int main()
{
char message1[]="Howdy";
cout << "message1: " << message1 << endl;
cout << "sizeof(message1): " << sizeof(message1) << endl;
char *msgPtr;
msgPtr = message1; // Try to compile and run without this line!
cout << "msgPtr (first): " << msgPtr << endl;
cout << "sizeof(msgPtr): " << sizeof(msgPtr) << endl << endl;
char message2[]="Here's a much longer message.";
cout << "message2: " << message2 << endl;
cout << "sizeof(message2): " << sizeof(message2) << endl;
msgPtr = message2;
cout << "msgPtr (second): " << msgPtr << endl;
cout << "sizeof(msgPtr): " << sizeof(msgPtr) << endl << endl;
char message3[]={'H','e','r','e',' ','w','e',' ','g','o'};
cout << "message3: " << message3 << endl;
cout << "sizeof(message3): " << sizeof(message3) << endl;
msgPtr = message3;
cout << "msgPtr (third): " << msgPtr << endl;
cout << "sizeof(msgPtr): " << sizeof(msgPtr) << endl << endl;
msgPtr = new char[56];
for(int i=0;i<10;i++) {
msgPtr[i]=65+i;
}
msgPtr[10]='';
cout << "msgPtr (fourth): " << msgPtr << endl;
cout << "sizeof(msgPtr): " << sizeof(msgPtr) << endl << endl;
cout << " Now enter 5 strings << " << endl;
char buffer[256];
int len;
for(int i=0;i<5;i++) {
cin >> buffer;
len=strlen(buffer);
cout << i << ". " << len << ": " << buffer << endl;
}
return 0;
}
Explanation / Answer
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
#include<cstring>
int main()
{
char sentence[256], tmpChar;
int inputIt = 0;
cout << "Please enter a string" << endl;
cin >> sentence;
cout << "Echoing that string: "<<sentence << endl << "Please enter a sentence (less than 256 characters): " << endl;
cin.ignore();
cin.getline (sentence,256);
cout << "This is that sentence not more than 256 characters. "<< endl << "You entered " << strlen(sentence) << " characters. And " << strlen(sentence) << " were removed from the stream." << endl;
cout << "Please give me an integer (between 0 and 51) : " << endl;
cin >> inputIt;
tmpChar= sentence[inputIt];
sentence[inputIt] = '0';
cout << " The sentence is now: " << sentence << endl << "This is that sentence "<<endl ;
sentence[inputIt] = tmpChar;
cout << " The original is now: " << sentence <<endl;
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.