簡體   English   中英

(C ++)從文本文件中讀取數字

[英](C++) Reading digits from text file

我有一個看起來像這樣的文本文件:

73167176531330624919225119674426574742355349194934 96983520312774506326239578318016984801869478851843 85861560789112949495459501737958331952853208805511

等共20條線。 我想做的是從文本文件中讀取每個數字,並將它們放入整數數組(一個元素=一位數字)。 我如何只能從此文本文件中讀取一位數字,而不是整行?

有幾種方法可以完成您要尋找的內容,在本文中,我將介紹三種不同的方法。 他們三個都假定您使用std::ifstream ifs ("filename.txt")打開文件,並且您的“ 數組 ”實際上是聲明為std::vector<int> v

在這篇文章的結尾,還有一些關於如何加快插入向量的建議。


我想保持簡單。

最簡單的方法是使用operator>>一次讀取一個char ,然后從返回的值中減去'0'

標准保證'0''9'是連續的,並且由於char只是在不同事物上打印的數值,因此可以將其隱式轉換為int

char c;

while (ifs >> c)
  v.push_back (c - '0');

我喜歡STL,但討厭編寫循環。

許多人將其視為“ c ++實現方法 ”,尤其是在與STL迷們交談時,盡管它需要編寫更多的代碼。

#include <algorithm>
#include <functional>
#include <iterator>

...

std::transform (
  std::istream_iterator<char> (ifs),
  std::istream_iterator<char> (), 
  std::back_inserter (v),
  std::bind2nd (std::minus<int> (), '0')
);

我不想編寫循環,但是為什么不使用lambda?

#include <algorithm>
#include <functional>
#include <iterator>

...

std::transform (
  std::istream_iterator<char> (iss),
  std::istream_iterator<char> (),
  std::back_inserter (v),
  [](char c){return c - '0';}
);

我的std::vector每次插入都會重新分配存儲空間嗎?

應該是。 為了加快處理速度,您可以在開始進行任何插入操作之前在向量中保留存儲空間,如下所示。

ifs.seekg (0, std::ios::end); // seek to the end of your file
v.reserve (ifs.tellg ()    ); // ifs.tellg () -> number of bytes in it
ifs.seekg (0, std::ios::beg); // seek back to the beginning
char digit;
std::ifstream file("digits.txt");
std::vector<int> digits;
// if you want the ASCII value of the digit.
1- while(file >> digit) digits.push_back(digit);
// if you want the numeric value of the digit.
2- while(file >> digit) digits.push_back(digit - '0'); 

暫無
暫無

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

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