阅读量:153
在C++中,可以使用文件流来读取txt文件内容。以下是一个简单的示例代码:
#include
#include
#include
int main() {
std::ifstream file("example.txt"); // 打开txt文件
if (file.is_open()) { // 检查文件是否成功打开
std::string line;
while (getline(file, line)) {
std::cout << line class="hljs-comment">// 逐行读取并输出内容
}
file.close(); // 关闭文件
} else {
std::cout << "无法打开文件" << std class="hljs-keyword">return 0;
}
在上面的示例中,我们首先包含了必要的头文件,然后使用ifstream类来打开txt文件。然后我们使用getline函数逐行读取文件内容并输出到控制台,最后关闭文件。
请注意,您需要将上述代码中的example.txt替换为您要读取的实际txt文件的路径。