繁体   English   中英

为什么cout没有输出字符串

[英]Why there is no output from cout for the string

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM