c++ - 需要在c ++中将连续空格读取为单词
问题描述
我需要从文件中读取单词并将它们存储在字符串对象数组中。但是,问题是我需要将多个空格视为一个单词。例如,
I am.
这只是两个单词,它们之间有三个三个空格。但是,我需要证明这一点:
arr[0]="I"
arr[1]=" "
arr[2]=" "
arr[3]="am"
谁能帮帮我?这是我写的代码:
strSet = new std::string[noStrings];
file.open(filename);
if (file) {
unsigned int i = 0;
while (file>>strSet[i])
{
i++;
}
}
解决方案
如您所知,file >> string
确实会忽略任何空白字符逐字阅读。
据我所知,记录空格的最简单方法是读取整行,然后再解析该行。这是我的实现:
#include <iostream>
#include <fstream>
#include <vector>
std::vector<std::string> readWords(std::ifstream& file, size_t reservedSize = 0) {
std::string buffer;
std::vector<std::string> words;
words.reserve(reservedSize);
//while there is still something to read
while (file.good()) {
//read a line
std::getline(file, buffer);
for(size_t start = 0, end = 0; start < buffer.length();) {
//if a space is encountered
if (buffer[start] == ' ') {
//ignore the first space
++start;
end = start;
//count how many consecutive spaces
while(end < buffer.length() && buffer[end] == ' ')
++end;
//save spaces as separete strings
for (; start != end; ++start)
words.emplace_back(" ");
}
else {
//skip all whitespace characters, except ' '
while(start < buffer.length() &&
buffer[start] == '\v' &&
buffer[start] == '\r' &&
buffer[start] == '\n')
++start;
//count how many consecutive non whitespace characters
while(end < buffer.length() && !isspace(buffer[end])) ++end;
//add to array
words.push_back(buffer.substr(start, end - start));
//don't forget to increment start to avoid
//infinite loops
start += end - start;
}
}
}
//return the array
return words;
}
int main() {
std::ifstream stream("input.txt");
auto words = readWords(stream);
for (const auto& e : words) {
std::cout << '\'' << e << "'\n";
}
}
文件 input.txt('\' 不在文件中,它们显示行结束的位置):
I am.\
hello fellow friend \
输出:
'I'
' '
' '
'am.'
' '
'hello'
'fellow'
' '
'friend'
' '
' '
' '
推荐阅读
- amazon-web-services - 没有地址的 EKS 入口 - 尝试测试我的 EKS 集群
- javascript - Discord.js 机器人,如何在没有引脚的情况下清除?
- javascript - 如何使用我的 svelte firebase + sendgrid 电子邮件功能修复 500 错误
- python-2.7 - pip install 在命令行中不返回任何内容
- git - 列出 a 和 b 之间的 Git 提交,仅考虑 b 的第一父母和 a 的第一父母
- javascript - 自动生成 Hreflangs
- kubernetes - GCP kubernetes - 入口报告:所有后端服务都处于不健康状态
- sql - 如何计算每个特定值的不同值的数量
- firebase - 在运行时切换 google-services.json
- javascript - 尝试将 ObjC 与 JXA 一起使用:最简单示例中的 TypeError