C++:打印数据,printf

标签 c++ c++11 io

在以下代码的末尾,我获得了输出并使用 cout(在第 60 行)将其打印在终端上。但是,我想在文本文件中打印它,但在这种情况下我不能使用 fprintf。

我该怎么做?

这是我的代码:

#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;
}

最佳答案

使用 std::ofstream 并创建一个文件变量:

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

请在有关文件 I/O 的部分查看您最喜欢的 C++ 引用资料。

这是与 C 语言不同的地方之一。

关于C++:打印数据,printf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33679386/

相关文章:

C 程序验证错误和跳过用户输入

java - 如何在 Java 中测量磁盘速度以进行基准测试

c++ - 无法从 Array<float> 到 Array<int> 进行可行的转换

c++ - CMAP 上的 MFC C++ 查找

c++ - 使用指针的 strcat 实现

c++ - 非阻塞套接字在 Windows 上丢失数据

c++ - 如果包为空,是否对可变参数包类型执行替换?

c++ - 为什么我们不能有 move 的迭代器?

c++ - 不可能的隐式 move 操作?

java - 如果找到该单词,则仅替换文件该行中的该单词