如何将 .txt 文件中的文本读入数组?

新手上路,请多包涵

我想打开一个文本文件并完整读取它,同时使用 c++ 将其内容存储到变量和数组中。我在下面有我的示例文本文件。我想将第一行存储到一个整数变量中,第二行存储到一个 3d 数组索引中,最后一行存储到一个字符串数组的 5 个元素中。我知道如何打开文件进行读取,但我还没有学会如何读取某些单词并将它们存储为整数或字符串类型。我不确定如何在 c++ 中完成此操作,非常感谢任何帮助。

 3
2 3 3
4567 2939 2992 2222 0000

原文由 Flower 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 850
1 个回答

读取文本文件中的所有整数:

 #include <fstream>

int main() {
    std::ifstream in;
    in.open("input_file.txt")
    // Fixed size array used to store the elements in the text file.
    // Change array type according to the type of the elements you want to read from the file
    int v[5];
    int element;

    if (in.is_open()) {
        int i = 0;
        while (in >> element) {
            v[i++] = element;
        }
    }

    in.close();

    return 0;
}

原文由 Polb 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题