我有一个看起来像的文件:
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;
}
答案 0 :(得分:6)
考虑使用std::string
和op>>(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();
}