C++检查行尾
C++ check end of line
我在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
}
使用它将解决您的问题
相关文章:
- valgrind-hellgrind与泄漏检查的结果不同
- C++模板来检查友元函数的存在
- 检查输入是否不是整数或数字
- 试图让变量检查数组中的某些内容
- 检查值是否在集合p1和p2中,但不在p3中
- C++概念:如何使用'concept'检查模板化结构的属性?
- 概念TS检查忽略私有访问修饰符
- 检查 std::shared_ptr<> 的当前底层类型是否为 T
- 在c++中检查长方体是否尽可能快地重叠(无迭代)
- 如何在C++中检查2D数组中负值的输入验证
- C++:正在检查LinkedList中的回文-递归方法-错误
- 使用for循环检查数组中的重复项
- 如何检查一个c++字符串中有多少相同的字符/数字
- 检查不带转换的扫描格式
- 如何检查线程是否锁定
- 清除前检查矢量
- 如何处理来自核心指南检查器的关于gsl::at的静态分析警告
- C++LDAP检查用户是否是特定组的成员
- 检查TCHAR数组输入是否为带符号整数C++
- 用概念检查属性的类型