我有一个 txt 文件,其中包含格式为 12345678-A 的数字以及中间的一些随机数字和文本。我需要读取该文件并仅将 8 位整数保存到数组中。我该怎么做?
我当前的代码,如果只有数字,则有效:
const int MAX = 1000;
ifstream file("file.txt");
int data;
int index = 0;
int bigdata[MAX];
while (!file.eof() && index < MAX)
{
file >> data;
if (data > 20000000 && data < 90000000)
{
bigdata[index] = data;
index++;
}
}
Run Code Online (Sandbox Code Playgroud)
输入文本示例:
48251182-D 6,5 6
49315945-F 7 3
45647536-I 3,5 3
45652122-H 7 6,5
77751157-L 2 2,5
75106729-S 2 5
77789857-B 4 3 3,5 3
59932967-V 4 8,5
39533235-Q 8 8,5
45013275-A 5 2
48053435-Y 6 8
48015522-N 3,5 4
48015515-T
48118362-B 7,5 3,5
39931759-Q 5,5 3
39941188-D 3,5 1,5
39143874-I 3,5 4
48281181-O 6,5 6
Run Code Online (Sandbox Code Playgroud)
如果您需要的只是去掉每行中的第一个数字,那么您可以使用流operator >>读取整数部分,然后使用std::getline该行的其余部分。使用
std::vector<int> data;
ifstream fin("file.txt");
int number;
std::string eater;
while (fin >> number) // get first 8 digit number. stops at the '-'
{
data.push_back(number);
std::getline(fin, eater); // consume the rest of the line
//now we are on the next line
}
// now data has all of the numbers that start each line.
Run Code Online (Sandbox Code Playgroud)