簡體   English   中英

C ++ ifstream只讀整數

[英]C++ ifstream read only integers

我有一個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++;
    }
}

輸入文字范例:

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

如果只需要去除每行中的第一個數字,則可以使用流的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.

你需要這個:

...
#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...
   ...
}
...

解決此問題的一種方法是逐字符讀取流並搜索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。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM