为什么我的小c ++代码表现异常? [英] Why is my small c++ code behaving unexpectedly?

查看:120
本文介绍了为什么我的小c ++代码表现异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

// using structures
#include <iostream>
#include <string>
using namespace std;

struct playerinfo
{
    string name;
    int level;
};

int main()
{
    playerinfo arr[5];
    for (int i = 0; i < 5; i++)
    {
        cout << " enter name for player " << i << endl;
        getline(cin, arr[i].name, '\n');
        cout << " and level \n";
        cin >> arr[i].level;
    }
    for (int i = 0; i < 5; i++)
        cout << "the level of player " << arr[i].name << " is " << arr[i].level << endl;
}



我正在读一本关于c ++语法的书,我想让代码要求用户填写玩家和级别的名称,然后代码打印所有的代码。但它不是这样的行为。当我运行代码,输入播放器的名称说汤姆猫然后代码询问级别,我打印一个整数说100,然后意外的事情开始发生,其原因,我无法理解。你能帮忙吗?
edit-几个人问我详细说明什么意想不到的事情开始发生。意想不到的是,当我输入播放器的名称和播放器0的级别,屏幕上的下一个输出是输入播放器1和级别的名称,而我希望它应该只输出 c>使用从格式化的输入切换时,

I am reading a book on c++ syntax and I am practicing. I want the code to behave such that the code asks the user to fill in the names of the players and the levels and then the code prints them all. But it is not behaving like this. when I run the code and enter the name of the player say " tom cat" then the code asks the level and I print an integer say "100", and then unexpected things start happening, the reason of which, I am unable to understand. Can you please help? edit- few people have asked me to elaborate what "unexpected things" start happening. The unexpected thing is that when I type in the name of the player and the level of player 0, the next output on the screen is " enter name for player 1 and level " whereas I expect that it should only output "and level" after I enter the name of the player 1.

推荐答案

operator>>(),例如,在 cin> arr [i] .level 和未格式化的输入,例如使用 std :: getline()输入:整数的格式化输入在找到空格时立即停止,例如换行符。另一方面, std :: getline()将在找到换行符后立即停止!所以你收到一个空行。修复是在切换到未格式化的输入时跳过前导空白,例如:

When switching from formatted input using operator>>(), e.g., in cin >> arr[i].level and unformatted input, e.g., using std::getline() you need to be aware of whitespace potentially waiting in the input: the formatted input of an integer stops as soon as it finds a whitespace, e.g., a newline. On the other hand, std::getline() will stop as soon as it find a newline! So you receive an empty line. The fix is to skip leading whitespace when switching to unformatted input, e.g.:

std::getline(std::cin >> std::ws, arr[i].name);

机械手 std :: ws 当使用 std :: istream

时也应该始终验证您的输入是否成功使用它们之前:如果任何输入失败,流停止运行并转换为 false

You should also always verify that your inputs were successful before using them: if any input fails, the stream stops functioning and converts to false:

if (std::cin >> arr[i].level) {
    // process the data
}
else {
    // report that the input is wrong and bail out
}

这篇关于为什么我的小c ++代码表现异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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