gpt4 book ai didi

c++ - 为什么 cout 没有输出字符串

转载 作者:行者123 更新时间:2023-11-28 04:18:52 25 4
gpt4 key购买 nike

我在批改同学作业(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 将输出插入符号移至行首,随后的输出将覆盖该单词。

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

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

关于c++ - 为什么 cout 没有输出字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55924677/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com