c++

c++中ignore空格有哪些技巧

小樊
81
2024-09-25 03:17:15
栏目: 编程语言

在C++中,如果你想忽略字符串中的空格,可以使用以下几种方法:

  1. 使用std::cin.ignore()函数:这个函数可以读取并忽略输入流中的指定数量的字符。例如,如果你想忽略一行中的所有空格,你可以这样做:
#include <iostream>
#include <limits>

int main() {
    std::string input;
    std::getline(std::cin, input);
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    // 现在input中不包含空格
}
  1. 使用std::istringstream类:这个类可以将一个字符串转换为一个输入流,你可以使用它的>>运算符来读取字符串中的单词,这样就可以自动忽略空格了。例如:
#include <iostream>
#include <sstream>
#include <string>

int main() {
    std::string input = "Hello World";
    std::istringstream iss(input);
    std::string word;
    while (iss >> word) {
        // 现在word中不包含空格
        std::cout << word << std::endl;
    }
}
  1. 使用正则表达式:C++的<regex>库提供了对正则表达式的支持,你可以使用它来匹配并删除字符串中的空格。例如:
#include <iostream>
#include <string>
#include <regex>

int main() {
    std::string input = "Hello World";
    std::string output = std::regex_replace(input, std::regex("\\s"), "");
    // 现在output中不包含空格
    std::cout << output << std::endl;
}

0
看了该问题的人还看了