[英]getline can't get the first line of the file
嗨,我是新來的,需要我的協助才能完成任務。 我想從文件中讀取數據。 我使用過getline,但它不會讀取文件中的第一行,有人可以幫我嗎? 這是我的代碼:
void test(std::ifstream& infile, string& a, string& b, string& c)
{
infile >> a;
infile >> b;
infile >> c;
}
int main()
{
ifstream file_("Level1.txt");
string line;
string a, b, c;
while (getline(file_, line))
{
test(file_, a, b, c);
}
cout << a << " " << b << " " << c;
return 0;
}
在我的文件中:
aa
bb
cc
但輸出:
bb cc
Getline
正在獲取當前行,因此您的字符串如下所示
a = "bb"
b = "cc"
c = ""
因為您已經閱讀了第一行並且存儲在第一line
。您可以僅檢查文件是否打開,然后調用test函數,因為它將從文件的開頭開始,而不會跳過第一行。
if(file_.is_open())
{
test(file_, a, b, c);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.