在纠正配偶作业(OpenClassroom)期间,我遇到了这个奇怪的问题。
从字典文件中读取的字符串(1列300000行的单词,它太大了,不能把它放在这里但是给你一个想法
...
ABAISSAIS
ABAISSAIT
ABAISSAMES
ABAISSANT
...
)
与getline
没有出现在输出中(第70行)
actual | shuffledmysteryWord | userInput
expected mysteryWord | shuffledmysteryWord | userInput
我尝试用重组的绳子
for (int i=0; i<(motMystere.size()-1); i++) motMystere1 += motMystere[i];
并且它按预期工作,因此它不是空的,它完全可读,可能包含换行符(导致getline)字符串
还有很多其他事情可以/可能会得到纠正但是
码
#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>
#include <fstream>
using namespace std;
string melangerLettres(string mot)
{
string melange;
int position(0);
int wordSize=mot.size();
while ( wordSize > 1 )
{
if ( wordSize > 2 ) { position = rand() % (wordSize-1); }
else if ( wordSize == 2 ) { position = 0; }
melange += mot[position];
mot.erase(position, 1);
wordSize--;
}
return melange;
}
int main(void)
{
int compteur(0);
string motMystere, motMelange, motUtilisateur, motMystere1, ligne;
srand(time(0));
ifstream dico("dico.txt");
if (dico)
{
while (getline(dico, ligne))
{
++compteur;
}
dico.clear();
dico.seekg(0, ios::beg);
int nrandom = rand() % compteur;
for (unsigned int i = 0; i < nrandom; ++i)
{
getline(dico, ligne);
}
motMystere = ligne;
}
else
{
cout << "Erreur : lecture du fichier impossible\n";
return 1;
}
motMelange = melangerLettres(motMystere);
// dont know why but motMystere is just broken
//~ for (int i=0; i<(motMystere.size()-1); i++) motMystere1 +=
//~ motMystere[i];
cin >> motUtilisateur;
cout << motMystere << " | " << motMelange << " | " << motUtilisateur
<< "\n";
return 0;
}
看来文本字典文件具有Windows格式换行符(CR / LF对),而您运行的系统只需要一个换行符(LF)。当你读到一个单词时,CR(\r
)字符是单词中的最后一个字符。当您使用cout
输出时,此CR将输出插入符移动到行的开头,后续输出将覆盖该单词。
您可以使用调试器检查这一点,检查其中一个单词的长度,和/或在\n
之后立即向cout
添加motMystere
字符。
解决方法是在读取后检查单词的最后一个字符,如果是CR字符则删除它。 (当你看到getline
时,你可以改变\r
停止,但是你必须跳过下一个可能是换行符的字符。)