C++ 将"Already Formatted"数组从文件读取到 Int 数组?
C++ Reading "Already Formatted" Array from file into an Int Array?
所以我打开了一个文件,里面有一堆参数,后面跟着读起来很好的整数;但是文件中的一个参数需要被读取到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
}
相关文章:
- 从锯齿状数组读取
- 是否很好地定义了强制转换为仅由 char[] 组成的结构并从该数组读取?
- 如何按字符从文件到2D数组读取字符
- 双维数组读取错误
- 动态分配的数组C 读取句子并打印单词
- ESP8266异常在尝试从字节数组读取float时
- C++无法从 2D 字符串数组读取
- Win32 C/C++从字节数组读取BMP宽度和高度
- 在执行期间将大型多维数组读取和写入二进制文件并返回数组
- 从 BYTE 数组读取 32 位整数.VC++
- 从十六进制数组读取 Int
- 从十六进制数组读取双精度到向量
- 通过数组C++读取学生的成绩
- 使用迭代器数组读取稀疏信息
- 从文件到字符串再到数组读取数字
- 直接从数组读取时超出了绑定地址
- 转换为空指针后从char数组读取int值
- 动态数组读取
- 从字节数组读取类型的模板方法的问题
- 从文件中以单独的数组读取整数,每次一个数字,在c++中