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; }
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; }
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!