获取关键字值C++
Get keyword value C++
我正在使用C++来读取文件并进行一些计算。我需要保存关键字的值,但我遇到了问题。我设法逐行读取文件并在字符串中找到关键字。但是如果我用 cout 检查它,或者如果我将其分配给一个变量并使用 cout 打印它,我会得到不同的结果。
该文件具有以下格式vtk 数据文件版本 2.0
#Generated by lpp.py
ASCII
DATASET POLYDATA
POINTS 3 float
我使用的代码是:
#include <string.h>
#include <string>
#include <fstream>
#include <iostream>
using namespace std;
int main(){
int nPart = 0;
string fileName = "liggghts_simPart";
string extension = ".vtk";
string keyword = "POINTS";
string currentFile;
string line;
int numLines = 0; // counter for line reading
currentFile = "liggghts_simPart0500.vtk";
//Open the curren file
ifstream fileToOpen;
fileToOpen.open(currentFile);
for (int i = 0; numLines <= 4 && getline(fileToOpen, line); ++numLines){
}
cout << line << endl;
size_t found = line.find(keyword);
nPart = line[ found + keyword.size() + 1 ]; // get key value
cout << line[ found + keyword.size() + 1 ] << endl;
cout << nPart << endl;
}
我得到的输出是
POINTS 3 float
3
51
那么为什么我会得到不同的输出呢?在这两种情况下,我都应该得到关键字的值,即 3。
如果有人能帮我一把,那就太好了!
谢谢毛罗
发生这种情况是因为您在没有正确转换值的情况下强制转换为int
。在 ASCII 中,符号"3"
的数值是 51
,这是您获得的输出。
您应该使用 std::stoi
转换为整数
nPart = std::stoi(line.substr(found + keyword.size() + 1, 1));
但是,如注释中所述,用于查找值的方法仅适用于个位数。如果你可能遇到大于 9
的值,你应该找到一种更好的方法来标记字符串(例如,通过" "
拆分(。
相关文章:
- Visual Studio 2015:Extern "C" 和 "export" 关键字
- C++中的"inline"关键字
- 如何确保C++函数在定义之前声明(如override关键字)
- 谷歌模拟和覆盖关键字
- 结构体 S { int align; } 之间的区别;(struct 关键字后的名称)和 struct { int al
- 如果全局变量默认是外部变量,为什么要添加"extern"关键字?
- 当我从下面的代码中删除关键字 virtual 时,它可以正常工作,否则会出现错误。在这里"virtual"字的意义是什么?
- 为什么"delete"关键字不删除节点?
- 在 c++ 中正确定义"this"关键字?
- 这个额外的关键字在这个 c++ 类声明中是什么意思?
- 在 typedef 内部使用 const 关键字和在 typedef 外部使用 const 关键字之间有区别吗?
- C++ - 为什么这里需要'template'关键字?
- C++函数的关键字?
- 使用 'typename' 关键字将非类型视为依赖上下文中的类型
- "friend"关键字在C++中是什么意思?
- 声明C++数组(带或不带 "new" 关键字)
- 对齐和对齐的实际用例C++关键字
- 在 c++ 中三元运算符中不允许继续(关键字)吗?
- 考虑到其他好处,关键字'auto'真的有助于简化调试C++吗?
- 在 Objective-C++ -> EXC_BAD_ACCESS Error 中使用"new"关键字