"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Why Does Turbo C++\'s \"cin\" Only Read the First Word?

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

Published on 2024-11-05
Browse:599

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:

#include 

class String {
  char str[100];

public:
  void input() {
    cout > str;
  }
  void display() {
    cout 

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3