本文介紹了如何在 C++ 中逐行讀取文件中的整數組的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我有一個文本文件,每行一個或多個整數,用空格分隔.我怎樣才能用 C++ 以優雅的方式閱讀這個?如果我不關心行,我可以使用 cin >>,但重要的是在哪一行整數上.
I have a text file with on every line one or more integers, seperated by a space. How can I in an elegant way read this with C++? If I would not care about the lines I could use cin >>, but it matters on which line integers are.
示例輸入:
1213 153 15 155
84 866 89 48
12
12 12 58
12
推薦答案
這取決于您是要逐行還是完整地進行.將整個文件轉化為一個整數向量:
It depends on whether you want to do it in a line by line basis or as a full set. For the whole file into a vector of integers:
int main() {
std::vector<int> v( std::istream_iterator<int>(std::cin),
std::istream_iterator<int>() );
}
如果您想在一行一行的基礎上進行交易:
If you want to deal in a line per line basis:
int main()
{
std::string line;
std::vector< std::vector<int> > all_integers;
while ( getline( std::cin, line ) ) {
std::istringstream is( line );
all_integers.push_back(
std::vector<int>( std::istream_iterator<int>(is),
std::istream_iterator<int>() ) );
}
}
這篇關于如何在 C++ 中逐行讀取文件中的整數組的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!