简体   繁体   English

C ++中的空格识别

[英]whitespace identification in c++

My code has to identify whitespace characters using cin, so when I use space as an input it should identify the space. 我的代码必须使用cin识别空格字符,因此当我使用空格作为输入时,它应该识别空格。 How do I do this? 我该怎么做呢?

You can use std::noskipws to disable the whitespace skipping that std::cin does by default: 您可以使用std::noskipws禁用默认情况下跳过std::cin的空格:

#include <iostream>
#include <iomanip>

int main() {
  char c;
  std::cin >> std::noskipws;
  while (std::cin >> c) {
    if (c == ' ')
      std::cout << "A space!" << std::endl;
  }
  return 0;
}
string str;
getline(cin, str); // get the whole line

If you want to deal with c-strings you could use the mentioned cin.getline(....) which is different from strings getline . 如果要处理c字符串,可以使用上述cin.getline(....) ,它与字符串getline不同。

Cin breaks on whitespace, of any kind. Cin打破了任何空白。 If you need to read an entire line, you need to use the get line function: 如果需要读取整行,则需要使用get line函数:

getline(cin, line);

Where line is a std::string. 其中line是std :: string。 This will still cut off any new lines or carriage returns. 这仍然会切断所有新行或回车符。

To test the string for spaces examine every character in the string and compare it to the space character " ". 要测试字符串中的空格,请检查字符串中的每个字符,并将其与空格字符“”进行比较。 That is left as an exercise for the reader ;) 那留给读者练习;)

Use cin.getline to read the line with the space. 使用cin.getline读取带有空格的行。

http://www.cplusplus.com/reference/iostream/istream/getline/ http://www.cplusplus.com/reference/iostream/istream/getline/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM