Why does the same program giving different outputs when inputs are given through different methods?
Program 1:
int main(){
char s[10];
cout << "Enter a String\n";
cin >> s;
cout << "The entered String is\n";
cout << s << "\n";
return 0;
}
When I give input through command line “Hello World”, the output I’m getting is only “Hello”
Program 2:
int main(){
char s[] = "Hello World";
cout << "The entered String is\n";
cout << s << "\n";
return 0;
}
In this case, I’m getting output of “Hello World”.
What is the difference between both programs? Is the logic the same? How can I obtain the whole string “Hello World” when entered through the command line? Is there a way?
Use
getline():The problem with your code is that the input stream extraction operator
>>only gets characters up to the next whitespace (so, just one “word”). Thegetline()function gets the whole line.