如果你真的想解析一个字符一个字符,那么你有很多工作。而且,你有点依赖你的环境。行可以用 '\n' 或 '\r' 或 "\r\n" 终止。
我真的建议使用一个旨在获得完整线路的函数。而这个函数是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 并从文件中读取。没有区别。