Home > Backend Development > C++ > How to Read Spaces from Standard Input in C ?

How to Read Spaces from Standard Input in C ?

Barbara Streisand
Release: 2024-12-05 02:22:10
Original
151 people have browsed it

How to Read Spaces from Standard Input in C  ?

How to Read Spaces from Standard Input in C

When reading input using cin in C , spaces are typically ignored by default. This can be problematic if you intend to process characters including spaces. Here's how to address this issue:

One approach is to use the noskipws manipulator before cin. This manipulator explicitly instructs cin to read all characters, including whitespace.

int main() {
  char a[10];
  // Enable reading spaces
  cin >> noskipws;

  for (int i = 0; i < 10; i++) {
    cin >> a[i];

    if (a[i] == ' ') {
      cout << "It is a space!!!" << endl;
    }
  }

  return 0;
}
Copy after login

Alternatively, you can use the get function to read individual characters from the stream. get retrieves characters until it encounters a newline or the specified number of characters.

int main() {
  char a[10];

  // Read 10 characters into the array 'a'
  cin.get(a, 10);

  for (int i = 0; i < 10; i++) {
    if (a[i] == ' ') {
      cout << "It is a space!!!" << endl;
    }
  }

  return 0;
}
Copy after login

Both methods allow you to read spaces from the standard input stream and process them accordingly.

The above is the detailed content of How to Read Spaces from Standard Input 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