简体   繁体   English

C ++-cin.get(array,int)不读取第一个字符

[英]C++ - cin.get(array,int) not reading first char

I'm new to C++ and I'm trying some exercises. 我是C ++的新手,正在尝试一些练习。 The first one I wanted to do already got me in trouble. 我想做的第一个已经给我带来了麻烦。 The goal of the exercise is to reverse the string you input. 练习的目的是反转您输入的字符串。 This is easy. 这很容易。 But when in try to limit the amount of characters with cin.get(array,int) it removes the first character. 但是,当尝试使用cin.get(array,int)限制字符数量时cin.get(array,int)它将删除第一个字符。

Code: 码:

char voornaam[7];
cin >> voornaam;
cin.get(voornaam,7);

cout << voornaam[6] << voornaam[5] << voornaam[4] << voornaam[3] << voornaam[2] << voornaam[1] << voornaam[0] << endl;

This is the code. 这是代码。 So this should normally work but when I try it for example with Sander, it outputs 'redna' and then terminates. 因此,这通常应该可以工作,但是当我使用Sander进行尝试时,它会输出“ redna”,然后终止。

Any thoughts on how to fix this. 关于如何解决此问题的任何想法。 I would like a solution with cin.get(array,int) and not with an other function of cin . 我想用cin.get(array,int)而不是cin的其他功能的解决方案。

Thanks. 谢谢。

Well, this is funny. 好吧,这很有趣。 At first instance everything is fine. 乍一看一切都很好。 But with one minor thing. 但是有一件小事。 Notice 注意

cin >> voornaam

followed by 其次是

cin.get(voornaam,7)

What happens here is, when first prompt comes, you enter Sander. 这里发生的是,当第一个提示出现时,您输入Sander。 Hence, voornaam[0] = 'S' , voornaam[1] = 'a' and so on. 因此, voornaam[0] = 'S'voornaam[1] = 'a' ,依此类推。 And you press enter. 然后按回车。 cin.get(voornaam, 7) takes this as \\0. cin.get(voornaam, 7)将其设为\\ 0。 So, your voornaam looks something like 所以,你的voornaam看起来像

voornaam[0] = '\0'
voornaam[1] = 'a'
voornaam[2] = 'n' 

and so on. 等等。

And when you reverse it, you get "redna". 而当您反转它时,您会得到“ redna”。 So, do not use, cin twice, or enter full string twice to get the correct result. 因此,请勿使用cin两次,也不要输入两次完整的字符串以获取正确的结果。

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

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