【问题标题】:Using getline to read data from a file in C++在 C++ 中使用 getline 从文件中读取数据
【发布时间】:2014-06-03 09:11:07
【问题描述】:

我想从文件中读取两件事,全名(名字和姓氏) 和年龄。之后,我想将它们存储在一个数组中,然后打印数据。 但是,当我尝试读取第一条记录时是 read find,而其他两条则不是。 请告诉我我错过了什么。 谢谢。

文件内容为:

sampleFirst1 sampleLast1
30
sampleFirst2 sampleLast2
25
sampleFirst3 sampleLast3
40

输出是:

Name:  sampleFirst1 Age: 30
Name:  Age: 30
Name:  Age: 30

这是我的代码:

#include "Person.h"
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
    ifstream inputFile("data.txt", ios::in);
    string full_name;
    int age = 0;

    int i = 0;
    Person personArray[3];
    while (i < 3)
    {
        getline(inputFile, full_name);
        personArray[i].set_name(full_name);
        inputFile >> age;
        personArray[i].set_age(age);
        ++i;
    }
    inputFile.close();
    printData(personArray, 3);
    cout << endl;
    return 0;
    }

【问题讨论】:

  • 你为每一行增加 i,而不是为每个人。
  • 'getline(inputFile, full_name);'您是否正在尝试将一行文本读入 int ?那是怎么编译的?
  • 对不起,这不是我刚刚更正类型的重点。
  • sdotdi,你是什么意思?你能澄清更多吗?

标签: c++ file input


【解决方案1】:

您不应该以这种方式混合getline&gt;&gt; 运算符。喜欢这样一个更简单的代码:

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

struct Person {
  std::string name;
  int age;

  void set_name(std::string const& i_name) { name = i_name; }
  void set_age(int i_age) { age = i_age; }
};                                                                                                                                                                                        

int main()
{
  ifstream inputFile("data.txt", ios::in);
  std::string first;
  std::string last;
  int age = 0;

  int i = 0;
  std::array<Person,3> personArray;
  while (i < personArray.size())                                                                                                                                                                                                                  {
    inputFile >> first >> last >> age;
    personArray[i].set_name(first + " " + last);
    personArray[i].set_age(age);
    ++i;
  }
  inputFile.close();

  for(Person const& person : personArray) {
    std::cout << "Name: " << person.name << " Age: " << person.age << "\n";
  }
  std::cout << std::flush;

  return 0;
}

如果您不想为全名支付额外的字符串连接费用,也可以只使用getlineistringstream 来填充年龄。

解析方法可以说很多,但这不是重点。

【讨论】:

  • 完美!正是我想要的。谢谢。
猜你喜欢
  • 1970-01-01
  • 2018-11-01
  • 1970-01-01
  • 2013-02-28
  • 2016-07-15
  • 2015-01-21
  • 2014-12-11
  • 1970-01-01
  • 2015-06-11
相关资源
最近更新 更多