[英]getline() function in C++ does not work
我用C ++編寫了一個代碼,它打開一個.txt文件並讀取其內容,將其視為(MAC地址數據庫),每個mac地址都以(。)分隔,我的問題是在我搜索了文件總數后行數,我無法將指針返回到文件的初始位置,在這里我使用seekg() and tellg()
來操縱指向文件的指針。
這是代碼:
#include <iostream>
#include <fstream>
#include <conio.h>
using namespace std;
int main ()
{
int i = 0;
string str1;
ifstream file;
file.open ("C:\\Users\\...\\Desktop\\MAC.txt");
//this section calculates the no. of lines
while (!file.eof() )
{
getline (file,str1);
for (int z =0 ; z<=15; z++)
if (str1[z] == '.')
i++;
}
file.seekg(0,ios::beg);
getline(file,str2);
cout << "the number of lines are " << i << endl;
cout << str2 << endl;
file.close();
getchar();
return 0;
}
這是MAC.txt文件的內容:
0090-d0f5-723a。
0090-d0f2-87hf。
b048-7aae-t5t5。
000e-f4e1-xxx2。
1c1d-678c-9db3。
0090-d0db-f923。
d85d-4cd3-a238。
1c1d-678c-235d。
here the the output of the code is supposed to be the first MAC address but it returns the last one .
file.seekg(0,ios::end);
我相信你想要file.seekg(0,ios::beg);
這里。
從結尾開始的零偏移量( ios::end
)是文件的結尾。 讀取失敗,您將剩下在緩沖區中讀取的最后一個值。
同樣,一旦達到eof
,就應該使用file.clear();
手動將其重置file.clear();
在您尋求之前:
file.clear();
file.seekg(0,ios::beg);
getline(file,str2);
如果在執行文件操作時檢查錯誤,則該錯誤將更容易捕獲。 有關示例,請參見Kerrek SB的答案。
您的代碼正在犯各種錯誤。 您永遠不會檢查任何錯誤狀態!
這應該是這樣的:
std::ifstream file("C:\\Users\\...\\Desktop\\MAC.txt");
for (std::string line; std::getline(file, line); )
// the loop exits when "file" is in an error state
{
/* whatever condition */ i++;
}
file.clear(); // reset error state
file.seekg(0, std::ios::beg); // rewind
std::string firstline;
if (!(std::getline(file, firstline)) { /* error */ }
std::cout << "The first line is: " << firstline << "\n";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.