为什么字符串没有 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)字符串
还有很多其他事情可以/可能会被纠正,但是
- 这不是我的代码
- 我只是对字符串感到好奇
法典
#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
时停止,但随后您必须跳过下一个字符,这将是换行符。
相关文章:
- 为什么在C的循环中使用printf的Rust代码不显示输出,而在C++的循环中显示std::cout
- std::cout输出int时出现编译错误
- COUT 无法提供输出可能是由于内联组装
- 为什么我的 cout 在输出中没有显示字符串?
- 调用 cout 时如何在结构中输出常量文本?
- 如何在C++中编写 ostream 的向量,它接收所有不同的输出流,如 cout、ostringstream 和 ofs
- Vscode/C++ - cout 无法输出完整的句子,也无法与整数连接
- 我的 cout 上有一个奇怪的输出,它把答案放在第一位,然后在我调用它的地方放一个奇怪的输出.我该怎么办?
- 在 CPP 中使用 cout 的重复输出
- 在 c++ 中使用 cout.precision() 的奇怪输出
- 为什么'std::cout << !+2 '输出 0?
- 对于输出,std::copy是否比std::cout快
- 在视觉工作室中以十六进制进行位移位并通过 cout 输出
- 输出使用 cout 转换为 ASCII 的文本时输出格式不正确,C++
- 如何从控制台 c++(从 cout)捕获输出
- 为什么cout输出内存地址不是字符串?
- Jupyter笔记本未显示C 输出(COUT)
- 输出 cout 是感叹号.C++
- 无法从C++循环实现所需的输出 (COUT)
- "定向到标准输出(cout)"是什么意思?