Why there is no need of for loop in array with char datatype to get the input | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Why there is no need of for loop in array with char datatype to get the input

In this program I can just simply name the array with size and get the input. #include<iostream> using namespace std; int main() { char a[10]; cin>>a; cout<<a; return 0; } But I case of int variable, why we have to use loop to get the input and output, #include<iostream> using namespace std; int main() { int a[5],i; for(i=0;i<5;i++) { cin>>a[i]; } for(i=0;i<5;i++) { cout<<a[i]; } return 0; }

1st Jan 2023, 2:21 AM
Devesh Tiwari
Devesh Tiwari - avatar
1 Answer
0
Characters arrays are used as strings in C++ and C (there is a string class in C++ too). In a lot of places, you'll see special behaviour of characters arrays because they're treated as strings In the first code, by taking input into a character array, you're basically taking a string as input, and placing it's characters in your array. This is special behaviour of cin defined for character arrays It's the same with printing - if you print an integer array, you'll get a pointer in the output, but if you print a character array, the whole array will be printed as a string (till a '\0' is countered) Again, this behaviour of cout was separately defined for character arrays
1st Jan 2023, 3:58 AM
XXX
XXX - avatar