简体   繁体   English

如何在 C++ 中将文本记录拆分为文本文件

[英]How do I split a record of text into text file in C++

So I'm working on a simple file manipulating project where I need to append a new text on a single line, so, to visualize that suppose I have a text file called main.txt and in that file it contains a row of text that looks like this:所以我正在做一个简单的文件操作项目,我需要在一行上附加一个新文本,所以,假设我有一个名为main.txt的文本文件,并且在该文件中它包含一行文本看起来像这样:

[AB]
1
2

Now that lets say I want to add another text: [CB] & 4,5 , then I want the updated file to looked like this:现在假设我想添加另一个文本: [CB] & 4,5 ,那么我希望更新后的文件看起来像这样:

[AB] [CB]

1     4

2     5

But turns out it looked like this instead:但事实证明它看起来像这样:

[Ab]
1
2
    [CB]
    4
    5

Here's what I've tried so far这是我到目前为止尝试过的

#include <iostream>
#include <stdio.h>
#include <fstream>
#include <string>

int main() {

    std::ofstream file("C:\users\USER\Documents\CPPPRoject\nice.txt",std::ios::out|std::ios::app);
    file << "\t" << "[CB]" << "\n";
    file << "\t" << 4 << "\n";
    file << "\t" << 5 << "\n";

    return 0;
}
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
    // we have only 1 column in this example and also we have only 2 rows of data
    int columnCount = 1, dataRows = 2;
    string newColumnName;
    int data1, data2;
    cout << "enter the column name: ";
    cin >> newColumnName;
    // getting the new datas based on the amount of the rows
    int *data = new int[dataRows];
    for (int i = 0; i < dataRows; i++)
        cin >> data[i];
    // opening the orginal.txt and pasting it into copy.txt with new data
    fstream original, copy;
    original.open("original.txt", ios::in);
    copy.open("copy.txt", ios::out);
    // copy & paste the columns
    string inStr;
    for (int i = 0; i < columnCount; i++)
    {
        original >> inStr;
        copy << inStr << " ";
    }
    copy << newColumnName << "\n";
    // copy past the columns
    int inData;
    for (int i = 0; i < dataRows; i++)
    {
        for (int j = 0; j < columnCount; j++)
        {
            original >> inData;
            copy << inData << "    ";
        }
        copy << data[i] << "\n";
    }
    original.close();
    copy.close();
    // deleting the original and renaming the copy.txt
    remove("original.txt");
    rename("copy.txt", "original.txt");
    return 0;
}

this is a simple code to add a column to the text file which only have 1 column of data , for doing it to larger file you can adjust columnCount and dataRows .这是一个简单的代码,用于将一列添加到只有 1 列数据的文本文件中,对于更大的文件,您可以调整columnCountdataRows

sample test of code :代码示例测试:

original.txt before running the code运行代码之前的 original.txt

[AB]
5
6

program inputs ( column name and new data to insert)程序输入(列名和要插入的新数据)

enter the column name: [CD]
1 2

original.txt file after execution of the code执行代码后的 original.txt 文件

[AB] [CD]
5    1
6    2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM