溫馨提示×

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

c++
小樊
82
2024-09-25 03:17:15
欄目: 編程語言

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

  1. 使用std::cin.ignore()函數(shù):這個函數(shù)可以讀取并忽略輸入流中的指定數(shù)量的字符。例如,如果你想忽略一行中的所有空格,你可以這樣做:
#include <iostream>
#include <limits>

int main() {
    std::string input;
    std::getline(std::cin, input);
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    // 現(xiàn)在input中不包含空格
}
  1. 使用std::istringstream類:這個類可以將一個字符串轉(zhuǎn)換為一個輸入流,你可以使用它的>>運算符來讀取字符串中的單詞,這樣就可以自動忽略空格了。例如:
#include <iostream>
#include <sstream>
#include <string>

int main() {
    std::string input = "Hello World";
    std::istringstream iss(input);
    std::string word;
    while (iss >> word) {
        // 現(xiàn)在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"), "");
    // 現(xiàn)在output中不包含空格
    std::cout << output << std::endl;
}

0