C++ 读取和追加

C++ Read and append

大家好,我正在做的一项练习需要帮助。我搜索了很多但没有找到我要找的东西。 所以,我希望我的程序从一个 .txt 文件中读取,然后在另一个 .txt 文件中给出输出。

Source File have this contents.
Name Salary 
Aamir 12000 
Amara 15000
Adnan 13000
Afzal 11500

Output File should have this 
Name Salary 
Aamir 14000
Amara 17000
Adnan 15000
Afzal 13500

程序应该读取源文件并在输出文件中将 2000 加到工资中。

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
    char c;
    char inputFile[] = "my-file.txt";
    char outputFile[] = "my-file-out.txt";

    ifstream inFile;
    ofstream outFile;

    inFile.open(inputFile, ios::in);

    if (!inFile)
    {
        cout << "The file cannnot be open please check" << endl;
        exit(1);
    }

    outFile.open(outputFile, ios::out | ios::ate);

    while ((c = inFile.get()) != EOF)
    {

        outFile.put(c);
    }

    inFile.close();
    outFile.close();
}

经过一番努力,我能够将内容从源文件复制到输出文件,但现在无论我做什么,都不会给我理想的解决方案。我应该在代码中添加什么才能给出正确的输出。

  1. const char*
  2. 更喜欢使用 const std::string
  3. 提取第一行并写入输出流。 std::getline可以帮到你。
  4. 如果您的源数据由固定类型的数据组成,请使用 operator>> 从源读取数据。
  5. 加薪并用operator<<
  6. 写入dest文件

以下代码有效,但为简单起见,我省略了异常或错误处理。您应该在打开、读取、写入数据和关闭流时添加处理代码。

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

using std::string;

int main() {
  const string name_input_file = "D:/my-file.txt";
  std::ifstream ifs(name_input_file);

  const string name_output_file = "D:/my-file-out.txt";
  std::ofstream ofs(name_output_file);

  string fist_line;
  std::getline(ifs, fist_line);
  ofs << fist_line << '\n';

  string name;
  int salary;
  while (ifs && ofs) {
    ifs >> name >> salary;
    salary += 2'000;
    ofs << name << ' ' << salary << '\n';
  }

  return 0;
}

这是一个肮脏的解决方案。读取 my-file.text,将 2000 添加到每个薪水并将新字符串写入 my-file-out.txt。请注意,每次 运行 程序时 my-file-out.txt 将丢失其以前的数据。

#include <algorithm>
#include <fstream>
#include <iostream>
#include <iterator>
#include <string>

int main()
{
  std::ifstream ifile;
  std::ofstream ofile;
  ifile.open("my-file.txt", std::ifstream::in);
  ofile.open("my-file-out.txt", std::ofstream::out | std::ofstream::trunc);
  std::string line{};
  bool flag{true};

  while (std::getline(ifile, line))
  {
    if (flag){ flag = false; ofile << line << "\n"; continue; }
    std::string salary{};
    for (size_t i{line.length() - 1}; i >= 0; --i)
    {
      if (line[i] == ' ') break;
      salary += line[i];
    }
    std::reverse(salary.begin(), salary.end());
    line.replace(line.length() - salary.length(), line.length(), std::to_string(std::stoi(salary) + 2000));
    ofile << line << "\n";
  }

  ifile.close();
  ofile.close();
}