为什么这段代码表现得很奇怪(比如它跳过了一行)? [英] Why this code behaves weirdly (like it skipped a line)?

查看:74
本文介绍了为什么这段代码表现得很奇怪(比如它跳过了一行)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C ++的新手。



Hi, I'm new to C++.

void getName(std::string &name, const int &playerNum){
    cout<<"Enter name for player"<<playerNum<<": ";
    std::getline(cin,name);
}

void player(){
    std::string playerOne, playerTwo;
    getName(playerOne, 1);
    getName(playerTwo, 2);
}

int main(){
    player();
    return 0;
}



在程序中它没有等待getName(playerOne,1),而是继续使用getName(playerTwo,2)获取。为什么会这样?

我真的认为我在这里错过了一些简单的东西。



我尝试过的事情:



之前我曾尝试


In the program it did not wait for getName(playerOne,1) but instead continue to getline for getName(playerTwo,2). Why it happen?
I really think that I actually missed something simple here.

What I have tried:

previously I tried

std::string getName(std::string &name, const int &playerNum){
    cout<<"Enter name for player"<<playerNum<<": ";
    std::getline(cin,name);
    return name;
}



但它会产生分段错误。我仍然不明白为什么会这样。


but it produces segmentation error. Which I still didn't understand why it happen.

推荐答案

我刚试过你的代码,它运行正常。您确定已从程序中复制了确切的代码吗?此外,您不需要 playerNum 字段中的&符号(&),因为它是常量。
I just tried your code and it works fine. Are you sure you have copied the exact code from your program?. Also you do not need the ampersand (&) on the playerNum field as it is a constant.


尝试清除任何行在缓冲区之前 std :: getline

Try to clear any line in the buffer first before std::getline:
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');





祝你好运!



Good luck!


你应该学会尽快使用调试器。而不是猜测你的代码在做什么,现在是时候看到你的代码执行并确保它完成你期望的。



调试器允许你跟踪执行逐行检查变量,你会看到有一点它会停止你所期望的。

在Visual Studio 2010中掌握调试 - 初学者指南 [ ^ ]

http://docs.oracle.com/javase/7/docs/technotes/tools/windows/jdb.html [ ^ ]

https://www.jetbrains.com/idea/help/debugging-your-first-java-application.html [ ^ ]



[更新]

使用调试器启动你的程序并在当时执行1行。

并查看当你在 getName(playerOne)时会发生什么,1),查看消息是否按预期显示,输入同意。
You should learn to use the debugger as soon as possible. Rather than guessing what your code is doing, It is time to see your code executing and ensuring that it does what you expect.

The debugger allow you to follow the execution line by line, inspect variables and you will see that there is a point where it stop doing what you expect.
Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]
http://docs.oracle.com/javase/7/docs/technotes/tools/windows/jdb.html[^]
https://www.jetbrains.com/idea/help/debugging-your-first-java-application.html[^]

[Update]
Launch your program with the debugger and execute 1 line at the time.
and see what happen when you are in getName(playerOne, 1), see if the message is displayed as expected or not, idem for input.


这篇关于为什么这段代码表现得很奇怪(比如它跳过了一行)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆