c++ - 使用 getline 读取文件时遇到问题(菜鸟)

标签 c++ string syntax getline

我是一个菜鸟 C++ 学生。我在将文件读入数组结构时遇到问题。这是一项类作业,所以我不需要任何人为我编写代码,我只想知道我做错了什么。我正在阅读的文本文件格式如下:

Giant Armadillo#443#M
Hawaiian Monk Seal#711#M 
Iberian Lynx#134#M
Javan Rhinoceros#134#M etc...

使用 getline() 可以正确读取带有 '#' 定界符的字符串,但不适用于 int字符。如何在检查分隔符时读取 intchar? 谢谢,对不起,如果这写得不清楚,或者格式不正确。我是 SO 的新手。

#include <iostream>
#include<string>
#include <fstream>
#include <cstdlib>
using namespace std;

//Create a new structure
struct Endangered
{   
    string name;
    int population; 
    char species;
};


int main () {

Endangered animals[200];

//initialize animals
for (int i=0; i<50; i++)
{
    animals[i].name=" ";
    animals[i].population=0;
    animals[i].species=' ';
}

ifstream myFile;
myFile.open("animals.txt");
int i=0;
if (myFile.is_open())
{   
    while (myFile.eof())
    {   
        //read the string until delimiter #
        getline(myFile, animals[i].name, '#');

        //read the int until delimiter #
        getline(myFile, animals[i].population, '#');

        //read the char until the delimiter
        getline(myFile, animals[i].species, '/n');
        i++;
    }


    return 0;
}

最佳答案

我确定你不能像这样从文件中读取数据:

//read the int until delimiter #
getline(myFile, animals[i].population, '#');

因为你得到了 sting 并且你想将它分配给 int 或 char 字段。

看看这个声明:

istream& getline (istream& is, string& str, char delim);

您必须将字符串作为第二个参数。您不能将 int 或 char 和 animals[i].population 传递给此函数。population 是 int 类型。

您应该首先将数据加载到某个字符串或 char* 缓冲区,然后使用正确的函数将其转换为您想要的类型。例如,寻找像 atoi 这样的函数。

总结一下。读取数据到临时缓冲区,然后转换它。

如果这对您没有帮助,我会更正代码,但您不想:)

关于c++ - 使用 getline 读取文件时遇到问题(菜鸟),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15827681/

相关文章:

c++ - 我们如何有效地从数组中找到第二个最大值?

c++ - 字符串下标超出范围 - 我在哪里犯了错误?

javascript - Coffeescript 函数调用的括号

php - 正确的 SQL 语法(PHP 和 MySQL 组合)

python - 内联 for in 表达式评估

c++ - Boost UpgradeLockable概念

c++ - 使用 const cast 将 std 字符串转换为 char*

python - 训练 '\x00' s 和 TypeError : stat() argument 1 must be encoded string without null bytes, 不是 str

java - 是否有一种有效的实现来量化两个字符串之间的相似性?

c++ - 在 C++ 中处理不同的文件