Home > Backend Development > C++ > body text

Why Does Turbo C \'s \'cin\' Only Read the First Word?

Barbara Streisand
Release: 2024-10-28 18:07:29
Original
502 people have browsed it

Why Does Turbo C  's

Turbo C 's "cin" Limitation: Reading Only the First Word

In Turbo C , the "cin" input operator has a limitation when dealing with character arrays. Specifically, it only reads until it encounters a whitespace character (e.g., space or newline). This can lead to unexpected behavior when trying to read multi-word input.

Consider the following Turbo C code:

<code class="c++">#include <iostream.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();
}</code>
Copy after login

If you run this code and enter the input "Steve Hawking," you would expect the output to display the entire string. However, due to the "cin" limitation, only "Steve" is displayed, because "cin" stops reading at the first whitespace character (space).

Overcoming the Limitation

To address this limitation, you can use alternative methods for reading character arrays in Turbo C :

  1. cin.getline(str, sizeof str);
    This method reads an entire line of input, including whitespace characters, into the specified char array.
  2. std::getline(cin, str);
    If you have access to the standard library, you can use this method to read a whole line into a string object, which offers more flexibility.
  3. Implement your own string class:
    You can define your own string class that handles input and output more efficiently.

Recommendation

The recommended approach nowadays is to use modern C compilers and the standard library. This provides more reliable and efficient input handling, including the ability to read entire lines of input.

The above is the detailed content of Why Does Turbo C \'s \'cin\' Only Read the First Word?. 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!