Home  >  Article  >  Backend Development  >  Why does `cin >> str` only extract the first word in C ?

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

Susan Sarandon
Susan SarandonOriginal
2024-10-27 16:47:30844browse

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>

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>

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!

Statement:
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