The code sample is from http://www.lmpt.univ-tours.fr/~volkov/C++.pdf. Some of you may think string in C++ is better than cstring. You may consider this as a pedagogical purpose.
// C-string.cpp : Using C strings.
// -----------------------------------------------------
#include <iostream>
#include <iomanip>
#include <cstring>
using namespace std;
char header[] = "\n *** C Strings ***\n\n"; // define a c string
int main()
{
char hello[30] = "Hello ", name[20], message[80]; // define a c string hello, declare two other c strings name and message
cout << header << "Your first name: ";
cin >> setw(20) >> name; // Enter a word.
strcat( hello, name); // Append the name.
cout << hello << endl;
cin.sync(); // No previous input.
cout << "\nWhat is the message for today?"
<< endl;
cin.getline( message, 80); // Enter a line with a max of 79 characters.
if( strlen( message) > 0) // If string length is longer than 0.
{
for( int i=0; message[i] != '\0'; ++i)
cout << message[i] << ' ';
cout << endl;
}
return 0;
}
When I run the above code, the following is the output:
*** C Strings ***
$:~ ./a.out
Your first name: dfdfd
Hello dfdfd
What is the message for today?
$:~
On the other hand, if I make a small change to comment some lines as the following:
// C-string.cpp : Using C strings.
// -----------------------------------------------------
#include <iostream>
#include <iomanip>
#include <cstring>
using namespace std;
char header[] = "\n *** C Strings ***\n\n"; // define a c string
int main()
{
char hello[30] = "Hello ", name[20], message[80]; // define a c string hello, declare two other c strings name and message
/*
cout << header << "Your first name: ";
cin >> setw(20) >> name; // Enter a word.
strcat( hello, name); // Append the name.
cout << hello << endl;
cin.sync(); // No previous input.
*/
cout << "\nWhat is the message for today?"
<< endl;
cin.getline( message, 80); // Enter a line with a max of 79 characters.
if( strlen( message) > 0) // If string length is longer than 0.
{
for( int i=0; message[i] != '\0'; ++i)
cout << message[i] << ' ';
cout << endl;
}
return 0;
The output is:
What is the message for today?
fdjfdlfjl
f d j f d l f j l
My question: why?
EDIT: I hope it is not considered as a duplicate, as there is the other related question I asked earlier. Using std::getline() to read a single line?