使用 getline 读取字符串,但每行中都有换行符

Using getline to read into a string but there is newline appearing in each line

本文关键字:换行符 getline 读取 字符串 使用      更新时间:2023-10-16

我的文本文件看起来像这样:

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;
}