【发布时间】:2021-06-27 19:16:46
【问题描述】:
我正在尝试从文件 1 中获取文本,并通过用随机种子填充空格来证明文件 2 的内容。
似乎一切正常,但我无法到达输入文件的末尾。程序在读取某行时卡在循环中。
文件 1 供阅读
https://pastebin.com/raw/rRhcz3Tw
粘贴文件 1 后的文件 2
https://pastebin.com/raw/uRrJVdy3
我已经阅读了有关标志问题的信息,我想知道是否可能是这种情况?
我的代码:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
unsigned int plusLongueChaine(ifstream& file);
void ajoutEspace(string& ligne, const unsigned int maxChaine);
int main()
{
srand(time(0));
// Création des instances de lecture et écriture
ifstream fin("ip.txt", ios::in);
ofstream fout("ip2.txt", ios::out);
// Si le fichier n'est pas trouvé
if (!fin.is_open()) {
cerr << "Ouverture du fichier impossible." << endl;
return 1; // Prototype dans cstdlib
}
// 1 - Trouver la plus longue ligne dans le fichier
const unsigned int maxChaine = plusLongueChaine(fin);
string ligneAEcrire;
fin.clear();
fin.seekg(0, ios::beg);
// 2 - Boucle principale
while (getline(fin, ligneAEcrire)) {
if (ligneAEcrire.empty()) {
fout << "\n" << endl;
continue;
}
if (ligneAEcrire.size() < maxChaine)
ajoutEspace(ligneAEcrire, maxChaine);
fout << ligneAEcrire << endl;
}
cout << maxChaine; // 84
return 0;
}
void ajoutEspace(string& ligne, const unsigned int maxChaine) {
unsigned int position = 0;
while (ligne.size() < maxChaine) {
position = ligne.find(' ', position);
if (position < ligne.size() && position != string::npos) {
if (rand() & 1)
ligne.insert(position, "_");
position = ligne.find_first_not_of(' ', position);
cout << position << endl;
}
else {
position = 0;
}
}
}
unsigned int plusLongueChaine(ifstream& file) {
string ligne;
unsigned int longueurChaine = 0;
while (getline(file, ligne)) {
if (ligne.size() > longueurChaine)
longueurChaine = ligne.size();
}
return longueurChaine;
}
【问题讨论】: