Home > Backend Development > C++ > body text

Why does `cin >> str` only extract the first word in C ?

Susan Sarandon
Release: 2024-10-27 16:47:30
Original
843 people have browsed it

Why does `cin >> str` only extract the first word in C  ? 
> str` only extract the first word in C ? " />

cin Extracts Only First Word in C

In the provided code, cin's extraction of a string using cin >> str; captures only the first word, causing issues when dealing with input containing multiple words. This is due to the way cin operates in Turbo C , reading one word at a time when encountering >>.

Solution:

To extract a complete line into a character array instead of a single word, modify the cin statement to:

<code class="c++">cin.getline(str, sizeof str);</code>
Copy after login

Alternatively, if using a more modern C environment and working with strings, you can replace the char array with std::string and utilize getline() to read the input as follows:

<code class="c++">getline(cin, str);</code>
Copy after login

Additional Considerations:

  • It's highly recommended to update your compiler, as Turbo C 4.5 is significantly outdated and does not support modern C features. Visual Studio Express or other modern compilers are suggested for better compatibility.

The above is the detailed content of Why does `cin >> str` only extract the first word in C ?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!