C++ 将"Already Formatted"数组从文件读取到 Int 数组?

C++ Reading "Already Formatted" Array from file into an Int Array?

本文关键字:数组 读取 Int 文件 Already Formatted C++      更新时间:2023-10-16

所以我打开了一个文件,里面有一堆参数,后面跟着读起来很好的整数;但是文件中的一个参数需要被读取到ARRAY中,并且被格式化为纯文本,如下所示:

Demand = [6907,14342,36857,40961,61129,69578,72905,91977,93969,97336];

假设我已经将这一行读取为一个名为"line"的字符串;如何将这些数字拉入名为"Demand[]"的数组?

edit:实际数字只是示例,并不重要

如果您只想解析一个包含项目列表的字符串,请尝试以下操作:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
    const char *s="Demand = [6907,14342,36857,40961,61129,69578,72905,91977,93969,97336];";
    int count=0,Demand[20];
    char *pointer=strchr(s,'[');
    while(pointer && *pointer++!=']')
        Demand[count++]=strtol(pointer,&pointer,10);
    for(int i=0;i<count;++i) printf("%d ",Demand[i]);
    return 0;
}

当while循环开始计数为0并且指针指向下一个整数开始之前的字符(在本例中为,或[)时。while循环将指针移动到整数的开始,然后strtol将指针移到整数的结束(取决于,或]),计数在保存整数时递增。

使用substr函数将数据的必要部分,即6907143423685740961611296957872905919779396997336获取到临时字符串中。用空格替换临时字符串中的所有逗号。将临时字符串存储到字符串流对象中。然后从stringstream对象中读取空格分隔的数字,就像从cin中读取一样,并将其存储在您选择的向量或数组中。

#include<iostream>
#include<string>
#include<vector>
#include<sstream>
using namespace std;
int main()
{
    string line="Demand = [6907,14342,36857,40961,61129,69578,72905,91977,93969,97336]";
    string temp=line.substr(10,line.length()-(10+1));//Assuming 10 is the index of the first number  i.e. 6907 (here) and subtracting the number of characters skipped in the begining + ']' (10+1)
    int i=0;
    for(i=0;i<temp.length();++i)
        if(temp[i]==',')//Check if it is a comma
            temp[i]=' ';//Replace all commas with space
    vector<int> arr;
    stringstream ss;
    ss<<temp;//Store the string to a stringstream object
    int num;
    while(ss>>num)//Check whether stringstream has any remaining data
        arr.push_back(num);//If data is obtained from stringstream insert it to the integer vector
    for(i=0;i<arr.size();++i)
        cout<<arr[i]<<endl;//Output the vector data
}