当前位置:首页 C++ > 正文

c++从文件中读取字符串

作者:野牛程序员:2023-12-03 08:42:22 C++阅读 2739

使用C++从文件中读取字符串可以通过std::ifstream类实现。以下是一个简单的示例代码:

#include <iostream>
#include <fstream>
#include <string>

int main() {
    std::ifstream file("example.txt"); // 替换为你的文件名

    if (file.is_open()) {
        std::string str;

        // 从文件中读取字符串
        while (std::getline(file, str)) {
            // 在这里处理每一行的字符串,可以输出或进行其他操作
            std::cout << str << std::endl;
        }

        file.close();
    } else {
        std::cout << "无法打开文件" << std::endl;
    }

    return 0;
}

请确保替换文件名 "example.txt" 为要读取的实际文件名。这个程序将逐行读取文件内容并将每一行的字符串输出到标准输出。可以根据需要进行修改,比如将读取的字符串存储在数组或进行其他处理。


野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892
野牛程序员教少儿编程与信息学竞赛-微信|电话:15892516892
相关推荐

最新推荐

热门点击