gpt4 book ai didi

c++,对 ifstream 使用 get 和 >>

转载 作者:行者123 更新时间:2023-11-27 23:35:18 28 4
gpt4 key购买 nike

我有一个要从中输入数据的文本文件,但我似乎无法正确输入数据。

下面是文本文件中的两行作为示例(这些不是真实的人不用担心):

Michael    Davidson     153 Summer Avenue        Evanston        CO 80303
Ingrid Johnson 2075 Woodland Road Aurora IL 60507

这是我必须加载文本文件并将数据放入结构中的代码。我仍然是 C++ 的新手(很明显),我很难同时使用 get 和 >>。我下面的代码在我进入“状态”之前工作正常,然后出现问题。感谢您的帮助!

//constants
const int FIRST_NAME_LEN = 11;
const int LAST_NAME_LEN = 13;
const int ADDRESS = 25;
const int CITY_NAME_LEN = 16;
const int STATE_LEN = 3;

//define struct data types
struct CustomerType {
char firstName[FIRST_NAME_LEN];
char lastName[LAST_NAME_LEN];
char streetAddress[ADDRESS];
char city[CITY_NAME_LEN];
char state[STATE_LEN];
int zipCode;
};

//prototype function
ifstream& getInfo(CustomerType& CT_Struct, ifstream& infile);

int main() {

//declare struct objects
CustomerType CT_Struct;

ifstream infile("PGM951_customers.txt");
if(!infile) {
cerr << "Could not open the input file." << endl;
exit(1); //terminates the program
}

//call the function
getInfo(CT_Struct, infile);

return 0;
}

ifstream& getInfo(CustomerType& CT_Struct, ifstream& infile) {

while(infile) {
infile.get(CT_Struct.firstName, sizeof(CT_Struct.firstName));
infile.get(CT_Struct.lastName, sizeof(CT_Struct.lastName));
infile.get(CT_Struct.streetAddress, sizeof(CT_Struct.streetAddress));
infile.get(CT_Struct.city, sizeof(CT_Struct.city));
infile.get(CT_Struct.state, sizeof(CT_Struct.state));
infile >> ws;
infile >> CT_Struct.zipCode;

cout << CT_Struct.firstName << " | " << CT_Struct.lastName << " | " << CT_Struct.streetAddress
<< " | " << CT_Struct.city << " | " << CT_Struct.state << " | " << CT_Struct.zipCode << endl;
}

return infile;

}

===编辑===========在 8 个字符的状态下阅读只是我在胡闹,然后我忘了将其改回...抱歉。

最佳答案

问题是 istream::get() 中断了 streetAddress,其中有空格。

一种方法是首先将输入行标记化为 stringsvector,然后根据标记的数量将这些转换为 的适当字段>客户类型:

vector<string> tokenize(string& line, char delim=' ') {
vector<string> tokens;
size_t spos = 0, epos = string::npos;
while ((epos = line.find_first_of(delim)) != string::npos) {
tokens.push_back(line.substr(spos, epos - spos));
spos = epos;
}
return tokens;
}

我更喜欢 CustomerType 的流提取操作符:

struct CustomerType  {
friend istream& operator>>(istream& i, CustomerType& c);
string firstName, lastName, ...;
// ...
};

istream& operator>>(istream& i, CustomerType& c) {
i >> c.firstName >> c.lastName;
string s1, s2, s3;
i >> s1 >> s2 >> s3;
c.streetAddress = s1 + s2 + s3;
i >> c.city >> c.state >> c.zipCode;
return i;
}

关于c++,对 ifstream 使用 get 和 >>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/831445/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com