2016-04-14 58 views
0

我有这种格式12345678-A数字加一些随机的数字和文本之间一个txt文件。我需要读取这个文件,并且只保存8位数字的整数。我该怎么做?C++ ifstream的只读整数

当前代码我有,作品,如果只是有一些数字:输入文本的

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++; 
    } 
} 

样品:

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 
+0

其实你的代码部分反正打破。哪个资源教你编写'while(!file.eof())'? [我们需要纠正它](http://stackoverflow.com/q/5605125/560648)。 –

+0

大概[此酮](http://stackoverflow.com/questions/2084265/reading-integers-from-a-text-file-with-words)上SO。 – 2016-04-14 12:42:08

+0

@RawN:不太可能。这是SO展示该问题的数百万个晦涩难懂的答案之一,下面有一条评论说“不要这样做”。我期待被告知哪本书或教科书是错误的。 –

回答

-1

一个解决这个问题将是读取字符流字符和搜索8位数字:

static const int MAX = 1000; 

int index = 0; 
int bigdata[MAX]; 

int value = 0; 
int digits = 0; 

for (auto c = file.get(); c != EOF 0; c = file.get()) 
{ 
    if (c >= '0' && c <= '9') 
    { 
     value = (digits ? (value * 10) : 0) + (c - '0'); 
     ++digits; 
     if (digits == 8) 
     { 
      if (index < MAX) 
       bigdata[index++] = value; 
      digits = 0; 
     } 
    } else 
    { 
     digits = 0; 
    } 
} 

该代码逐字节读取并构建如果读取了十进制数字,则为整数。如果数字计数达到8,则数字被存储并且整数缓冲器被重置。如果读取的字符不是十进制数字,则立即重置整数缓冲器。如果阅读过文件的末尾

istream.get()返回EOF所以不需要到.EOF()成员函数的调用。

请注意,此代码存储所有8位数字。如果您只需要20000000..90000000范围内的数字,则必须添加另一个测试。

如果你的线总是开头的8位数字后跟一个减号,那么你可以使用这个简单的解决方案,我建议,因为提高可读性。

std::string buffer; 
std::vector<int> target; 
while (std::getline(file, buffer)) 
    target.push_back(atoi(buffer.c_str())); 

但是这种解决方案不检查有效的数字的存在,并简单地对每一行不能以数字开始存储0。

+1

太复杂了。让图书馆肮脏的工作。 –

+0

我误读了这个问题,并写了代码从文件中读取任何8位数字。我的答案现在还包含一个简单的解决方案,从每行的开头读取数字。 –

+0

@AndreasH。我不得不处理一个文件,其中的数字不在每行的开头,并且您的第一个建议完美奏效,谢谢! – Constantine32

2

你需要这样的:

... 
#include <string> 
... 
string line; 
while (getline(file, line)) // read the whole line 
{ 
    int data = stol(line);  // get number at start of line (stops 
           // automatically at the '-' sign 

    // data is the 8 digit number 
    // process data here... 
    ... 
} 
... 
+0

谢谢!这正是我所寻找的,我在代码块中制作stol/stoi工作时遇到了麻烦,我不得不使用atoi(line.c_str());代替。很好地工作。 – Constantine32

3

如果你需要的是去掉每一行的第一个号码,然后你可以使用流的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.