使用.ignore('\n'),后面的Getline函数仅从文件获取一半的输入 [英] Used .ignore('\n') and the Getline function that follows is only taking half of the input from file

查看:80
本文介绍了使用.ignore('\n'),后面的Getline函数仅从文件获取一半的输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图确保我要问的不是重复的,因为这肯定是一个非常初学者的错误,但是我找不到类似的东西,但是如果有人引用了类似的帖子,那会很好无论如何都很好,所以我正在尝试制作一个战舰游戏,该游戏从.csv文件读取船的位置,但是在放置船之前,它会通过文件并确保在文件中找到所有船。

I tried to make sure what I'm asking wasn't a duplicate since this must be a very beginner mistake but I couldn't find something similar but if someone has a reference to a similar post that'd be great as well anyways So I'm trying to make a battleship game that reads in the ship placement from a .csv file but before it places the ships it goes through the file and makes sure all the ships are found in the file.

文件中的数据格式如下:

The data in the file is formatted as follows:

Carrier,B2,H
Battleship,D4,V
Cruiser,G4,H
Submarine,G5,V
Destroyer,G8,H

在我的代码中导致我出现问题的部分是此块:

The part that is causing me issues in my code is this block:

cout << "File successfully located!\n Making sure all ships are in file...\n";
while (shipPlacement.good()) {
        getline(shipPlacement, shipType, ',');
        cout << shipType << endl;
        shipPlacement.ignore('\n');
    }

我希望它只接受战舰类型,而忽略文件。正确读取了第一行,直到设置了定界符,它才停止读取,太棒了!然后我希望它忽略下一行直到下一行之前的所有内容,因此我放置了shipPlacement.ignore('\n'),从那时起,它应该再次循环读取下一个船,直到定界符,等等。这里有东西吗?发生的事情只是将一半的船型作为输入。这是我得到的输出:

I want it to only take in the battleship type and ignore everything else in the file. The first line is read in correctly it stops reading until the set delimiter, great! and then I want it to ignore everything that follows until the next line so I put shipPlacement.ignore('\n') and from that point it should loop again reading in the next ship up until the delimiter, etc. am I missing something here? what is happening is only half of the ship type is getting taken as input. This is the output I'm getting:

Making sure all ships are found in file...
Carrier
leship
ser
arine
royer

这是可能是一个简单的修复程序,但我看不到它的外观,感谢任何帮助或指导!

This is probably a simple fix but I can't see what's in front of me it looks like, Any help or guidance is appreciated!

推荐答案

ignore 的第一个参数是要丢弃的最大字符数,而不是定界符(并且由于您未指定定界符,因此它始终会丢弃最大值)。您的 \n 被二进制解释为数字10,这将导致接下来的10个字符被跳过(,B2,H⏎Batt)。您应该改用 shipPlacement.ignore(x,'\n'),其中 x 是您最多的字符曾经希望在换行符之前看到它。

The first argument to ignore is the maximum number of characters to discard, not the delimiter (and since you didn't specify a delimiter, it was always discarding the maximum). Your \n is being interpreted in binary as the number 10, which results in the next 10 characters being skipped (,B2,H⏎Batt). You should instead do shipPlacement.ignore(x, '\n'), where x is the most characters you ever expect to see before the newline.

这篇关于使用.ignore('\n'),后面的Getline函数仅从文件获取一半的输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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