简体   繁体   English

C ++:打印数据,printf

[英]C++: print data, printf

At the end of the following code I obtain the output and print it on the terminal using cout (at line 60). 在以下代码的末尾,我获得输出并使用cout将其打印在终端上(第60行)。 However, I would like to print it in a text file but I cannot use fprintf in this case. 但是,我想在文本文件中打印它,但是在这种情况下不能使用fprintf。

How could I do it? 我该怎么办?

This is my code: 这是我的代码:

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

using namespace std;

bool isnotdigit(char c)
{
   return !isdigit(c);
}

bool compare(const string s1, const string s2)
{
   auto itr1 = s1.begin(), itr2 = s2.begin();

   if (isdigit(s1[0]) && isdigit(s2[0]))
   {
      int n1, n2;
      stringstream ss(s1);
      ss >> n1;
      ss.clear();
      ss.str(s2);
      ss >> n2;

      if (n1 != n2)
         return n1 < n2;

      itr1 = find_if(s1.begin(), s1.end(), isnotdigit);
      itr2 = find_if(s2.begin(), s2.end(), isnotdigit);
   }

   return lexicographical_compare(itr1, s1.end(), itr2, s2.end());
}

int main()
{

   char out_file_name[500];
   snprintf(out_file_name, sizeof(out_file_name), "sort.txt");
   FILE *out_file;
   out_file = fopen(out_file_name, "w");
   cout << "Making output file: " << out_file_name << endl;   

   ifstream in("mydata.txt");

   if (in)
   {
      vector<string> lines;
      string line;

      while (getline(in, line))
         lines.push_back(line);

      sort(lines.begin(), lines.end(), compare);

      for (auto itr = lines.begin(); itr != lines.end(); ++itr)
        cout << *itr << endl;
    //fprintf(out_file,);
   }

   fclose(out_file);
   cout << "Output complete" << endl;

   return 0;
}

Use std::ofstream and create a file variable: 使用std::ofstream并创建一个文件变量:

std::ofstream output_file("output.txt");
if (output_file)
{
  output_file << "Hello there.\n";
  output_file.flush();
}

Please review your favorite C++ reference in the section about file I/O. 请在有关文件I / O的部分中查看您最喜欢的C ++参考。

This is one of those areas that differs from the C language. 这是与C语言不同的领域之一。

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

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