如何读取忽略制表符空格的行
how to read a line ignoring the tab spaces
嗨,这里有一个读取输入行的代码。但是我需要帮助来忽略行中的制表符甚至空白。
#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_iterator
和ostream_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 }
相关文章:
- 2D数组来自文本输入,中间有空格
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- 如何在C++中读取空格分隔的输入 当我们不知道输入的数量时
- 如何在c++中使用system()来运行包含空格的python脚本
- basic_string的前导/尾部不区分空格的特征
- 如何插入 4 个空格宽的制表符并将它们删除两个空格?
- 防止控制台在通道字符(在 c++ 中)中输入空格(即空格、制表符和换行符)
- C++:按制表符拆分字符串,但包含空格
- 如何将制表符长度与Qt中的多个空格相匹配
- 标记 CString 问题与制表符空格字符
- 知道文本文件中的列数,用空格或制表符分隔
- 如何检查字符串是否包含空格/制表符/换行符(任何空白内容)?
- 如何拆分具有空格和制表符区分的文件行
- 当数据包含空格时,如何将制表符分隔文件的内容加载到C++字符串的 2D 向量中
- 如何使用 cin 读取带有空格的输入,直到到达制表符
- 试图获得一个C++switch语句来识别空格、制表符等
- 如何读取忽略制表符空格的行
- c++打印给定用户输入整数的空格或制表符
- 计算新行、制表符和空格
- 处理空格(或制表符)分隔的文件"like"和数组 - C++