为什么字符串没有 cout 的输出

Why there is no output from cout for the string

本文关键字:输出 cout 字符串 为什么      更新时间:2023-10-16

在纠正同学的家庭作业(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)字符串

还有很多其他事情可以/可能会被纠正,但是

  1. 这不是我的代码
  2. 我只是对字符串感到好奇

法典

#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 impossiblen";
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 将输出插入符号移动到行首,后续输出将覆盖该单词。

您可以使用调试器检查这一点,检查其中一个单词的长度,和/或在motMystere之后立即向cout添加n字符。

解决方法是在读入单词后检查单词的最后一个字符,如果它是 CR 字符,则将其删除。 (您可以将getline更改为在看到r时停止,但随后您必须跳过下一个字符,这将是换行符。