Click here to Skip to main content
15,890,670 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i was reading a sample code in a c++ book and it had the code:
C++
#include <iostream>
#include <string>
#include <string.h>

using namespace std;

int main()
{
   cout << "enter a line of text: ";
   string userinput;
   getline (cin, userinput);

   char copyinput[20] = { '\0' };
   if (userinput.length() < 20)
   {
      strcpy(copyinput, userinput.c_str())
      cout << "this does not exceed the buffer";
   }
   else 
   {
      cout << "this exceeds the buffer!";
   }

   return 0;
}


the thing i don't understand is why they put a '\0' at the when initialising the 20th element of the array, copyinput. I tried the program without adding the '\0', and it still worked, so i dont know why they put it there. can you please help me??

What I have tried:

i dont know what to search up about this
Posted
Updated 21-Apr-21 20:01pm
v2

1 solution

char copyinput[20] = { '\0' }; is a declaration, not an assignment statement. It declares a char array containing 20 elements, and initializes the entire array to '\0'.

The 0 initialization is allowed shorthand for initializing an entire array to 0.
 
Share this answer
 
Comments
iwanttoaskquestions 22-Apr-21 0:57am    
thank you

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900