[英]Reading a text file C++
我正在嘗試從文本文件中檢索某些行。 我在用着:
#include <iostream>
#include <fstream>
using namespace std;
void parse_file()
{
std::ifstream file("VampireV5.txt");
string str= "Clan";
string file_contents;
while (std::getline(file, str))
{
file_contents += str;
file_contents.push_back('\n');
}
cout << file_contents;
file.close();
}
int main()
{
parse_file();
return 0;
}
我想得到唯一包含“Clan”的行,直到'\n'。 我試圖在while循環中添加一個if,但它沒有返回任何東西。
有沒有辦法讓它一次得到 1 行?
您的代碼幾乎是正確的,如下所示:它逐行讀取文件並將內容附加到您的字符串中。
但是,由於您只想要那一行,因此您還需要檢查您要查找的內容。
此代碼片段應該只為您提供以單詞“Clan”開頭的行。 如果要檢查字符串是否在行中的任何位置,請考慮檢查:= string::npos
。
void parse_file()
{
std::ifstream file("VampireV5.txt");
string str;
string file_contents;
while (std::getline(file, str))
{
if (str.find("Clan") == 0)
{
file_contents += str;
file_contents.push_back('\n');
}
}
cout << file_contents;
file.close();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.