C "cin" Only Reads the First Word
In C , the input stream operator >> typically reads a single word from an input source such as the keyboard. This can be problematic when attempting to read a string that contains spaces, as only the first word will be captured. This issue can be encountered while working with character arrays.
Consider the following code:
<code class="c++">#include <iostream.h> #include <conio.h> class String { char str[100]; public: void input() { cout << "Enter string :"; cin >> str; } void display() { cout << str; } }; int main() { String s; s.input(); s.display(); return 0; }
When running this code in Turbo C 4.5, only the first word of a string is displayed. This is because cin >> str reads only one word into the str character array. To read a complete line of input, including spaces, an alternate approach is required.
One option is to use the getline() function:
<code class="c++">#include <iostream> #include <string> using namespace std; int main() { string s; cout << "Enter string :"; getline(cin, s); cout << s; return 0; }</code>
This code will read the entire line of input, including spaces, into the s string. getline() can also be used to read into character arrays:
<code class="c++">#include <iostream.h> #include <conio.h> int main() { char str[100]; cout << "Enter string :"; cin.getline(str, sizeof str); cout << str; return 0; }
Alternatively, if you prefer to use the >> operator, you can modify the code as follows:
<code class="c++">#include <iostream.h> #include <conio.h> class String { char str[100]; public: void input() { cout << "Enter string :"; cin.getline(str, sizeof str); } void display() { cout << str; } }; int main() { String s; s.input(); s.display(); return 0; }</code>
With these modifications, the code will correctly read and display the entire input string.
The above is the detailed content of How to Read Entire Lines of Input Including Spaces with C \'s `cin`?. For more information, please follow other related articles on the PHP Chinese website!