简体   繁体   English

如何在文本文件中添加空格?

[英]How to add spaces into a text file?

I have a text file like this:我有一个这样的文本文件:

100,Nguyen Van A,2004
101,Tran Thi B,2004
102,Vo Van C,2005
103,Truong Thi D,2005

How can I add one blank space right after each "," into that file using C++?如何使用 C++ 在每个“,”之后添加一个空格到该文件中?

I've tried using find() function but nothing worked.我试过使用 find() function 但没有任何效果。

svFile.open("list_student.txt");
    while (getline(svFile, line, ','))
    {
        if (line.find(",", 0) != string::npos)
            svFile << " ";
    }

Two options, read and write the file character by character, or option 2, read the entire text file into a string and then perform your required changes and write the file back:两个选项,一个字符一个字符地读取和写入文件,或者选项 2,将整个文本文件读入一个字符串,然后执行所需的更改并将文件写回:

Option 1 (Character by Character):选项 1(逐个字符):

 char ch;
 fstream fin("list_student.txt", fstream::in);
 fstream fout("list_student_result.txt", fstream::out);
 while (fin >> noskipws >> ch) {
    fout << ch;
    if (ch==',')
    {
        fout << ' ';
    }
 }
 fout.close();

Option 2 (Read/Write entire file):选项 2(读/写整个文件):

#include <iostream>
#include <fstream>
int main()
{

    // Read the entire file
    std::ifstream t("list_student.txt");
    std::stringstream buffer;
    buffer << t.rdbuf();

    std::string myString = buffer.str();
    size_t start = 0;
    int pos = 0;

    // Set your start character and replace with string here
    std::string comma(",");
    std::string replaceWith(", ");

    // Replace the comma "," with ", " (and a space)
    while ((pos = myString.find(comma, pos)) != std::string::npos) {
        myString.replace(pos, comma.length(), replaceWith);
        pos += replaceWith.length();
    }

    // Write the formatted text back to a file
    std::ofstream out("list_student_result.txt");
    out << myString;
    out.close();

    return 0;
}

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

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