gpt4 book ai didi

c++ - 写入文件时保留空格

转载 作者:行者123 更新时间:2023-11-27 23:57:07 57 4
gpt4 key购买 nike

我有一个队列,其中填充了以下内容:

'c', 'c', 'c', 's', 'c', 'c', 'c', 'c', 's', 'c', 'c', 'n', 'c', 'c', 'c', 'e'

我正在尝试将以下内容写入 .txt 文件:

  • 如果队列前面是'c',找到连续'c'的数量,将该数字写入文件
  • 如果队列前面是's',写一个空格到文件
  • 如果队列前面是'n',写一个换行符到文件
  • 如果队列前面是'e',停止

我的算法如下:

void writeToFile(queue<char> &input) {
int numC;
ofstream myFile;
myFile.open("file.txt");
while (input.front() != 'e') {
if (input.front() == 'c') {
numC = 0;
while (input.front() == 'c') {
numC++;
input.pop();
}
myFile << numC;
} else if (input.front() == 's') {
myFile << " ";
} else if (input.front() == 'n') {
myFile << "\n";
}
input.pop();
}
myFile.close();
}

file.txt 应包含以下内容:

3 4 2
3

但它包含以下内容:

342
3

为什么文件里没有空格?如果重要的话,我会使用 Linux。

最佳答案

当你在内部循环中检查 'c' 时,你将 'c' 从队列中弹出直到到达 's',它随后完成循环和第一个 if block ,并继续执行 input.pop()外部 while 循环的末尾,它将您移动到下一个字符,因此永远不会根据您的 if 语句检查“s”。

关于c++ - 写入文件时保留空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41797647/

57 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com