出于无法理解的原因,我的代码编写了两次 [英] My code is written twice for uncomprehensible reasons
问题描述
这段代码是用C ++编写的,由于我不太理解的原因,它被编写了两次.我希望输入一个随机字符后,它将显示一次字符,并且字符串也将显示在其下.但是我没有得到这个作为输出.我想念什么?
This code is written in C++ and for reasons that I don't quite understand it is written twice. I would expect that after inputting a random char it would display the char once and the String lower to it once as well. But I don't get this as output. What am I missing?
解决方案:添加cin.ignore()语句也会忽略读入的返回值.使我的代码一次遍历循环.
Solution: Adding a cin.ignore() statement disregards the return that is read in as well. Making my code go through the loop once.
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int main()
{
char letter;
letter = cin.get();
while (letter!= 'X')
{
cout << letter << endl;
cout << "this will be written twice for ununderstandable reasons";
letter = cin.get();
}
}
示例:如果我要使用cmd scrn c
编写代码,则会得到一个 c
返回+两次短语,出于不可理解的原因,该短语将被编写两次
.所以我认为是输出
Example:
If I were to write in cmd scrn c
, I'd get a c
back + twice the phrase this will be written twice for ununderstandable reasons
. So what I thought to be the output
c
this will be written twice for ununderstandable reasons
实际上是
c
this will be written twice for ununderstandable reasons
this will be written twice for ununderstandable reasons
正如大家已经提到的,
推荐答案
,每次您按Enter键, cin
都会添加换行标记 \ n
.另一种解决方案是将 cin.ignore();
放在每个 cin.get();
之后.
as everyone already mentioned, cin
will append the newline marker \n
every time you hit enter. another solution is to place cin.ignore();
after every cin.get();
.
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int main()
{
char letter;
letter = cin.get();
cin.ignore();
while (letter!= 'X')
{
cout<<letter<<endl;
cout<<"this will be written twice for ununderstandable reasons";
letter= cin.get();
cin.ignore();
}
}
这篇关于出于无法理解的原因,我的代码编写了两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!