C++检查行尾

C++ check end of line

本文关键字:检查 C++      更新时间:2023-10-16

我在C++遇到了一个问题,我需要解析一个包含多行的文件(随机长度的随机字符串(并将大写字符转换为小写字符并将行存储在字符串向量中。我正在尝试逐个字符解析文件,但不知道如何识别行尾。

如果你真的想解析一行字符,那么你有很多工作要做。而且,您有点依赖于您的环境。行可以用""或"\r"或"\r"结尾。

我真的建议使用旨在获得完整行的功能。这个功能是std::getline.如果您的行不包含空格,您也可以使用提取器运算符直接读取字符串,如下所示:std::string s; ifstreamVariable >> s ;

为了独立于这种行为,我们可以实现一个代理类来读取完整的行并将其放入std::string中。

可以使用代理类和基于范围的矢量构造函数将文件读入向量。

为了转换为小写,我们将使用 std::transform .这很简单。

请参阅以下示例代码。

#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <sstream>
std::istringstream testDataFile(
R"#(Line 0 Random legth asdasdasfd
Line 1 Random legth asdasdasfd sdfgsdfgs sdfg
Line 2 Random legth asdasdasfd sdfgs sdfg
Line 3 Random legth a sddfgsdfgs sdfg
Line 4 Random legth as sds sg
)#");

class CompleteLine {    // Proxy for the input Iterator
public:
    // Overload extractor. Read a complete line
    friend std::istream& operator>>(std::istream& is, CompleteLine& cl) { std::getline(is, cl.completeLine); return is; }
    // Cast the type 'CompleteLine' to std::string
    operator std::string() const { return completeLine; }
protected:
    // Temporary to hold the read string
    std::string completeLine{};
};
int main()
{
    // Read complete source file into maze, by simply defining the variable and using the range constructor
    std::vector<std::string> strings{ std::istream_iterator<CompleteLine>(testDataFile), std::istream_iterator<CompleteLine>() };
    // Convert all strings in vector ro lowercase
    std::for_each(strings.begin(), strings.end(), [](std::string& s) { std::transform(s.begin(), s.end(), s.begin(), ::tolower); });
    // Debug output:  Copy all data to std::cout
    std::copy(strings.begin(), strings.end(), std::ostream_iterator<std::string>(std::cout, "n"));
    return 0;
}

这是实现此类问题的"更多"C++方式。

顺便说一下,您可以替换 istringstream 并从文件中读取。没有区别。

ifSteamObject.eof( ( 用于检查文件末尾

if(!obj.eof())
{
   //your code
}

使用它将解决您的问题