如何读取忽略制表符空格的行

how to read a line ignoring the tab spaces

本文关键字:制表符 空格 何读取 读取      更新时间:2023-10-16

嗨,这里有一个读取输入行的代码。但是我需要帮助来忽略行中的制表符甚至空白。

#include <iostream>
#include <sstream>

using namespace std;
int main()
{
string input;
string line;
 cout<< "Enter the input line" << endl;
 while (getline(cin, line))
   // while(cin >> line)
{
  stringstream in;
  in << line;
  //cout<<"What goen IN: " <<in<<endl;
  line = in.str();
  input = line ;
  cout<<"Input is:" << input <<endl;
 }
 cout<< "The input entered was: "<<endl;
 cout<< input<< endl;
}

示例输入:

Hello                 my name is brownie

应该读

hellomynameisbrownie

您可以尝试从您刚刚阅读的行中删除制表符和空白符,如下所示:

 #include <algorithm>
 using namespace std;
 input.erase(remove(input.begin(), input.end(), 't'), input.end());
 input.erase(remove(input.begin(), input.end(), ' '), input.end());

方法:

  • 一个字符一个字符地读入,而不是一次整行,并且只在字符串中添加非空白字符。
  • 读入整个字符串,然后删除制表符、空格等。

您可能希望分两部分完成此操作。首先读取整行,然后将该行的所有非空白字符复制到输出中。

std::string line;
while (std::getline(std::cin, line)) {
    std::istringstream buffer(line);
    std::copy(std::istream_iterator<char>(buffer),
              std::istream_iterator<char>(),
              std::ostream_iterator<char>(std::cout, ""));
    std::cout << "n";
}

istream_iterator<char>部分使用标准>>流提取器每次读取一个字符,该提取器将跳过所有空白字符(空格,制表符等)

当然,您也可以稍微手动地完成大致相同的事情:

while (std::getline(...)) {
    std::istringstream buffer(line);
    char ch;
    while (buffer >> ch)
        std::cout << ch;
}

您想要一次读取一行的原因,是因为operator>> for char也会将新行字符视为空白,因此,如果您只是直接从输入文件复制到输出文件与istream_iteratorostream_iterator它会工作得有点太好了-随着您想要删除的空白,它也会删除所有的新行,所以您最终将整个文件连接在一起成为一个长行。

无论何时在C/c++中处理与空格、制表符或其他空白字符有关的输入,都要使用getchar()实现。

    这是一种非常简洁易懂的代码编写方式
  • 它是用于实现其他输入函数的基本函数之一
  • 你不需要记住函数的输入。

    int c;//Beware of taking it as a char
    while((c=getchar())!=EOF){
         //Do whatever you want here
         //in your case ignore tab and store other characters in the array
    }