c++ - 写入输出文件

标签 c++

这有什么问题吗?这部分代码的格式类型与其他可用选项的格式相同,但这部分代码不写入输出文件。

else if (choice1 == 4) {
  int nodes[100];
  int b = 0;
  int number;

  cout << "Please give the nodes that you want to include in the sub-graph.\n"
       << "(press -1 to stop input): ";

  do {
    cin >> number;
    nodes[b++] = number;
    b++;
  } while (number != (-1));

  outfile.open("output.txt", ::ofstream::in | ::ofstream::out | ::ofstream::app);

  if (outfile.is_open()) {
    outfile << "nodes[0]" << nodes[1] << nodes[2];
  }

  cout << endl << "Report stored in file: output.txt." << endl;
}

最佳答案

你有:

do {
  cin >> number;
  nodes[b++] = number;
  b++;
} while (number != (-1));

我发现这个 do-while 循环中的代码有几个问题。

  1. 您正在将数字 -1 存储在 nodes 中。据我了解,-1 是停止的信号。存储它没有意义。
  2. 您在循环中将 b 递增两次。也许那是你的意图,也许这是一个疏忽。

上面的代码块可以改成:

while (true)
{
  cin >> number;
  if ( number == -1 )
  {
    break;
  }
  nodes[b++] = number;
}

关于c++ - 写入输出文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22826727/

相关文章:

python - Cython:无法调用共享库的非静态方法

c++ - 奇怪的基准测试结果

c++ - Tinygps 库中的 millis() 函数溢出

c++ - 无法用gcc打开图形文件gcov

c++ - 如何为 C++ 代码制作 64 个共享 64 位 Linux 兼容库 (*.so)

c++ - 去除重复字母-词更正

c++ - 从 char * 中的整数填充 vector<int>

c++ - Intel NCS2 vpu不支持动态批处理

c++ - 类(class)成员重新排序

c++ - 如果在获取锁时进程 fork ,则 boost 进程间互斥锁上的锁会发生什么情况?