C++ Program to Read and Store Chinese Poetry from a JSON File

This guide provides code examples to demonstrate reading Chinese poetry from a JSON file, storing it in a vector, and outputting the results to a text file. We'll explore both line-by-line and character-by-character reading methods.

1. Initializing a Vector with Poetry

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

using namespace std;

int main() {
    vector<string> poetry = {'静夜思','床前明月光,疑是地上霜。',
                             '举头望明月,低头思故乡。'};
    return 0;
}

This code snippet initializes a vector called 'poetry' with three strings containing lines of Chinese poetry.

2. Reading Poetry from JSON File (Line by Line)

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

using namespace std;

int main() {
    vector<string> poetry;
    ifstream in("x.json");
    string line;
    while (getline(in, line)) {
        poetry.push_back(line);
    }
    in.close();
    ofstream out("D:\\out.txt");
    for (auto p : poetry) {
        out << p << endl;
        cout << p << endl;
    }
    out.close();
    return 0;
}

This code reads the contents of 'x.json' line by line and stores each line as a string object in the 'poetry' vector. The output is then written to a file named 'out.txt' and also displayed on the console.

3. Character-by-Character Reading from JSON File

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

using namespace std;

int main() {
    vector<string> poetry;
    ifstream in("x.json");
    char c;
    string line;
    while (in.get(c)) {
        if (c == '\n') {
            poetry.push_back(line);
            line = "";
        } else {
            line += c;
        }
    }
    poetry.push_back(line);
    in.close();
    ofstream out("D:\\out.txt");
    for (auto p : poetry) {
        out << p << endl;
        cout << p << endl;
    }
    out.close();
    return 0;
}

In this code, we read 'x.json' character by character. When a newline character ('\n') is encountered, the current 'line' is added to the 'poetry' vector, and the 'line' variable is reset. After reading all characters, the final 'line' is added to the vector.

This guide provides the foundational code for reading and storing Chinese poetry from a JSON file in C++. You can adapt these examples to suit your specific needs, such as processing different file formats or manipulating the poetry data in various ways.

C++ Program to Read and Store Chinese Poetry from a JSON File

原文地址: https://www.cveoy.top/t/topic/nwCu 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录