使用 getline 读取字符串,但每行中都有换行符
Using getline to read into a string but there is newline appearing in each line
我的文本文件看起来像这样:
Florida FL
Nevada NV
New York NY
现在,当我使用 getline 读取文件并将其打印到控制台时,每行末尾都有一个换行符(除了最后一行)。不过,Getline应该摆脱换行符。那么它从何而来?
ifstream inFileAbb("abbreviation.txt", ios::in);
while(getline(inFileAbb, line)){
cout << line;
}
系统方法是分析所有可能的输入数据,然后在文本中搜索模式。在您的情况下,我们分析问题并发现
- 在字符串的末尾,我们有一些连续的大写字母
- 在此之前,我们有州名
- 我们不关心 LF 的回车或新行 CR 或两者的组合
因此,如果我们搜索状态缩写模式并将其拆分,则状态的全名将可用。但也许有尾随和前导空格。我们将删除它,然后结果就在那里。
对于搜索,我们将使用一个std::regex
.模式为:1 个或多个大写字母,后跟 0 或多个空格,后跟行尾。其正则表达式为:"([A-Z]+)\s*$"
我们不关心换行符或其他什么。我们搜索所需的文本。
如果可用,则结果的前缀包含完整的状态名。我们将删除前导空格和尾随空格,仅此而已。
请看:
#include <iostream>
#include <string>
#include <sstream>
#include <regex>
std::istringstream textFile(R"( Florida FL
Nevada NV
New York NY)");
std::regex regexStateAbbreviation("([A-Z]+)\s*$");
int main()
{
// Split of some parts
std::smatch stateAbbreviationMatch{};
std::string line{};
while (std::getline(textFile, line)) {
if (std::regex_search(line, stateAbbreviationMatch, regexStateAbbreviation))
{
// Get the state
std::string state(stateAbbreviationMatch.prefix());
// Remove leading and trailing spaces
state = std::regex_replace(state, std::regex("^ +| +$|( ) +"), "$1");
// Get the state abbreviation
std::string stateabbreviation(stateAbbreviationMatch[0]);
// Print Result
std::cout << stateabbreviation << ' ' << state << 'n';
}
}
return 0;
}
相关文章:
- 如何防止clang格式在流运算符调用之间添加换行符<<
- C/C++ - 查询平台相关的换行符(用于内存映射文件)
- 在 Stream C++ 文本之前有一个额外的换行符
- 流:CSV 文件中的换行符
- 如何在三元条件运算符中添加换行符和连接? :在 C++ 中
- Clang-格式:在多行语句之后的换行符上打开大括号
- 在输出流中插入换行符
- 防止控制台在通道字符(在 c++ 中)中输入空格(即空格、制表符和换行符)
- QProcess::readAllStandardOutput() 和换行符
- 如果有换行符,clang 格式不会附加大括号
- 提取后返回换行符的C++istream.get()
- 使用 getline 读取字符串,但每行中都有换行符
- 使用 getline 忽略用户输入中的制表符和换行符
- 在 C++ 中,get() 和 getline() 对换行符的处理方式不同
- 使用 getline 仅读取换行符或文本
- 使用 getline 或 istringstream 检测换行符
- 停止getline丢弃换行符
- c++getline似乎无法识别通过管道传输到stdin的输入中的换行符
- 使用getline()忽略空白/制表符/换行符
- 区分getline中的分隔符和换行符