C ++阅读"已经格式化"从文件到Int数组的数组?

时间:2014-10-22 01:01:10

标签: c++ arrays string ifstream getline

所以我打开一个带有一堆参数的文件,然后是读取正常的整数;但是文件中的单个参数需要被读入ARRAY,并且以纯文本格式化:

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

假设我已将此行读入名为" line&#34 ;;的字符串中我如何将这些数字拉入名为" Demand []"?

的数组中

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

2 个答案:

答案 0 :(得分:0)

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

#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移动指针到整数的末尾(到,或者)依赖)和count作为保存整数的一部分递增。

答案 1 :(得分:0)

使用substr函数将必要部分的数据(即6907,14342,36857,40961,61129,69578,72905,91977,93969,97336)获取到临时字符串中。 用空格替换临时字符串中的所有逗号。 将临时字符串存储到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
}