簡體   English   中英

從文件逐行讀取

[英]Read from a file line by line

我如何才能逐行讀取文本文件,然后使用相同的數組保存它們..

首先,似乎您正在using namespace std; 在您的代碼中。 不鼓勵這樣做。 這是我將如何使用std::vector 首先,您必須導入<vector>頭文件。

std::ifstream in_file("file.txt");
if (!in_file) { ... } // handle the error of file not existing

std::vector<std::string> vec;
std::string str;

// insert each line into vec
while (std::getline(in_file, str)) {
    vec.push_back(str);
}

std::ifstream.close()方法是在其析構函數中處理的,因此我們不需要包含它。 這更干凈,讀起來更像英語,並且沒有魔法常數。 另外,它使用std::vector ,這非常有效。

編輯:std::string[]作為每個元素的修改:

std::ifstream in_file("file.txt");
if (!in_file) { ... } // handle the error of file not existing

std::vector<std::string[]> vec;
std::string str;

// insert each line into vec
while (std::getline(in_file, str)) {
    std::string array[1];
    array[0] = str;
    vec.push_back(array);
}

引用getline表示數據已附加到字符串

Each extracted character is appended to the string as if its member push_back was called.

讀取后嘗試重置字符串

編輯

每次調用getline時,line都會保留舊內容,並在末尾添加新數據。

line = "";

將在每次讀取之間重置數據

暫無
暫無

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

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