为什么cout没有输出字符串

时间:2019-04-30 15:53:57

标签: c++ cout stdstring

在纠正队友的作业(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 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;
}

1 个答案:

答案 0 :(得分:1)

似乎文本字典文件具有Windows格式的换行符(CR / LF对),而您运行的系统仅要求一个换行符(LF)。当您读一个单词时,CR(\r)字符是单词中的最后一个字符。当您使用cout输出时,此CR将输出插入符号移至行的开头,随后的输出将覆盖单词。

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

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

相关问题