0

我有一个看起来像的文件:

4
Sam Stone
2000
Freida Flass
100500
Tammy Flass
5000
Rich Raptor
55000

我正在尝试从中读取,但 while 循环中的第一个 getline 始终不返回任何内容。int 4 被正确读取。

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <vector>
#include <string>

using namespace std;

const int SIZE = 60;


struct person
{
    string name;
    double money;
};

int main()
{
    char filename[SIZE];
    string input;
    char inputs [50];
    int value;
    int count = 0;
    vector<person> Members;

    ifstream inFile;
    inFile.open("carinfo.txt");
    if (!inFile.is_open()){ cout << "Could not open fle"; }

    inFile >> value;
    Members.resize(value);

    while (inFile.good())
    {
        inFile.getline(inputs, SIZE); //getline(inFile, input, '\n');
        inFile >> value;

        count++;
    }
    cout << "Total lines = " << count;

    system("pause");
    return 0;
}
4

1 回答 1

6

考虑使用std::stringop>>(std::istream, person)阅读元素,这对我有用

#include <string>
#include <vector>
#include <limits>
#include <fstream>
#include <iostream>
#include <iterator>

struct person
{
    std::string name;
    double money;
};

//read in 1 person
std::istream& operator>>(std::istream& is, person& p) {
    is >> p.money;
    is.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    std::getline(is, p.name);
    return is;
}

int main() {
    //open stream
    std::ifstream file("fname");
    //create vector, let the stream operators do the hard work
    std::vector<person> v((std::istream_iterator<person>(file)),
                           std::istream_iterator<person>());

    std::cout << "count: " << v.size();
}

http://en.cppreference.com/w/cpp/iterator/istream_iterator

于 2012-10-14T17:04:26.293 回答