需要解析整型字符串并获得空白
Need to parse a string of ints and get the white space
我有一个充满整型数(每行上的可变数量)的文件,用空格分隔。我要解析int,然后是space,然后是int,然后是space…直到换行字符,然后从新的行开始,直到eof。一个示例文件看起来像这样:
1 1 324 234 12 123
2 2 312 403 234 234 123 125 23 34
...
要获取整型,我可以这样做:
std::ifstream inStream(file.txt);
std::string line;
int myInt = 0;
while(getline(inStream, line)) {
std::stringstream ss(line);
while(ss) {
ss >> myInt;
//process...
}
}
我的问题是,是否有一种简单的方法可以从ss中获得空格和尾行字符?或者我最好的办法是假设每个索引后面有一个空格,并且在ss的末尾有一个换行符?像这样:
std::ifstream inStream(file.txt);
std::string line;
int myInt = 0;
while(getline(inStream, line)) {
std::stringstream ss(line);
while(ss) {
ss >> myInt;
// process...
// done with myInt
char mySpace = ' ';
// now process mySpace
}
char myNewLine = 'n';
// now process myNewLine
}
如果性能不是最重要的问题,那么下面将是针对您的输入格式的通用标记器。当然,这是否是一个可行的解决方案取决于您实际想要如何处理输入。
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
static void handle_number_string(std::string& literal) {
if (!literal.empty()) {
std::istringstream iss {literal};
int value;
if (iss >> value) {
std::clog << "<" << value << ">";
} else {
// TODO: Handle malformed integer literal
}
literal.clear();
}
}
int main(int argc, char** argv) {
for (int i = 1; i < argc; i++) {
std::string aux;
std::ifstream istr {argv[i]};
std::clog << argv[i] << ": ";
while (istr.good()) {
const int next = istr.get();
switch (next) {
case ' ':
handle_number_string(aux);
std::clog << "<SPC>";
break;
case 'n':
handle_number_string(aux);
std::clog << "<EOL>";
break;
default:
aux.push_back(next);
}
}
// Handle case that the last line was not terminated with 'n'.
handle_number_string(aux);
std::clog << std::endl;
}
return 0;
}
附录:我只有在绝对必要的时候才会这样做。正确处理所有可能性(多个空格,非换行空格,制表符,rn
,…)将需要大量的工作。如果您实际想要处理的是逻辑标记字段分隔符和行尾,那么手动解析空白似乎是错误的方法。如果您的程序仅仅因为用户对输入文件中的列进行了对齐(因此使用了可变数量的空格)而崩溃,那将是令人遗憾的。
试试这样:
std::ifstream inStream(file.txt);
std::string line;
int myInt;
while (std::getline(inStream, line))
{
std::stringstream ss(line);
ss >> myInt;
if (ss)
{
do
{
// process...
// done with myInt
ss >> myInt;
if (!ss) break;
char mySpace = ' ';
// now process mySpace
}
while (true);
}
char myNewLine = 'n';
// now process myNewLine
}
相关文章:
- Boost Asio SerialPort。无法创建并打开串口服务
- 如何插入十六进制值并发送到串口?
- 创建一个程序,该程序将一串数字作为输入,并输出偶数和奇数的总和
- 从串行读取并分别保存值
- 如何加入两个指针以将其串在一起并将其存储在数组或字符中
- 导致ESP32随机停止并触发看门狗计时器重新启动的串行数据包
- C 将字符串按空白空间将字符串拆分,除非将其封闭在引号中并存储在向量中
- 如何引用串变量并在有或没有指针的情况下进行敲击
- 将utf8编码的字符串转换为本地8位编码的字符串,并将无法确定的字符替换为空白
- 如何读取文件内容并将其保存到字符串类型变量?为什么有空白空间
- 将标准字符串转换为 ascii 字符并通过串行端口 c++ 发送
- 如何使一个整数向量忽略空白,并在C++中的每个元素上加2
- 从串行设备读取字节(并理解它们??)
- 编写一个程序,读取一串包含标点符号的字符,并写入被读取的内容,但删除了标点符号
- 汇编:循环遍历一串字符并交换它们
- 取一串字母并将它们放入数组中
- 如何使用空白作为分隔符对字符串进行标记并将标记输入到列表中
- 增强串行通信,COM端口被拒绝并出现错误"open: access is denied"
- 接收一串"chars",并尝试使用指针计算其中有多少个相同类型
- 为什么这段代码在试图将.txt放入向量并对其进行cout时会返回空白控制台