我想知道我是否可以從 C 檔案中的選定行中讀取數字。例如,如果我有 .txt 檔案,例如:
2 3
1 2 3 4
4 5 6 7
有 3 行,我怎樣才能只讀取第 2 行的數字而無需閱讀其他內容?
uj5u.com熱心網友回復:
除非您從上一次呼叫中知道第二行的確切檔案偏移量,否則您std::istream::tellg必須讀取第一行才能到達第二行的位置。您可以使用std::getline讀取第一行的函式作為 a std::string,也可以使用std::istream::ignore讀取并丟棄第一行,如下所示:
input.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
如果您確實知道第二行的確切偏移量,那么您可以呼叫std::istream::seekg以直接跳轉到該偏移量。
但是請注意,檔案偏移量不一定與您在以文本模式讀取檔案時看到的字符數相對應。例如,在不同的平臺上,行尾可能包含不同數量的字符,\n當以文本模式讀取檔案時,這些字符會被轉換為單個字符。但是,所需的檔案偏移std::istream::seekg量是二進制模式下的偏移量。因此,您通常不應該嘗試自己計算這樣的偏移量(除非您以二進制模式打開流,對于文本檔案不應該這樣做)。您應該只使用該函式std::istream::tellg來獲得這樣的偏移量。
uj5u.com熱心網友回復:
您可以使用 C 逐行讀取檔案
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(){
fstream newfile;
newfile.open("file.txt",ios::in);
if (newfile.is_open()){
string tp;
int i=0;
while(getline(newfile, tp)){
if (i==1) {
cout << tp << endl; // this will only print the second line
}
i =1;
}
newfile.close();
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/421213.html
標籤:
上一篇:如何將陣列傳遞給另一個函式?C
