获取关键字值C++

Get keyword value C++

本文关键字:C++ 关键字 获取      更新时间:2023-10-16

我正在使用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 的值,你应该找到一种更好的方法来标记字符串(例如,通过" "拆分(。