gpt4 book ai didi

c++读取txt文件并复制到两个类istream::peek()

转载 作者:行者123 更新时间:2023-11-28 05:21:10 25 4
gpt4 key购买 nike

istream& operator>>(istream& s, vector<Order>& ord) {

string c{};
bool got_customer = false;
Customer temp_customer{};
vector<Purchase>vec_purchase{};
while (s >> c) {
cout << "Erstes Wort der Zeile: "<<c << endl;

if (!got_customer) { //c[0] == '#'
c.erase(c.begin()); //löscht erstes Element vom string
int k_nummer{};
string k_vname{};
string k_nname{};
string k_plz{};
string k_stadt{};
k_nummer = stoi(c); //string to int
s >> k_vname >> k_nname >> k_plz>>k_stadt;
k_vname += " " + k_nname;
temp_customer = Customer(k_nummer, k_vname, k_plz, k_stadt);
got_customer = true;
} else {
string p_name{};
double p_preis{};
int p_menge{};
p_name = c;
s >> p_preis>>p_menge;
cout << p_name << " " << p_preis << " " << p_menge << endl;
vec_purchase.push_back(Purchase{p_name, p_preis, p_menge});
}

cout<<s.peek()<<endl;
if (s.peek() == '#') {
ord.push_back(Order{temp_customer, vec_purchase});
temp_customer = Customer{};
vec_purchase.clear();
got_customer = false;
}
}
}

这是txt文件:

#725454 Schenker Rudolf DE-30159 Hannover
Shirt 135.95 1
Tie 89.59 1
#987654 Orbison Roy US-TN37075 Hendersonville
Mug 1.49 3
T-Shirt 14.90 1
#123456 Petty Tom US-FL32641 Gainesville
Flashlight 12.95 2
#246802 Hite Bob US-CA90291 Venice
CannedBeans 0.89 10
CannedTomatoes 1.79 6
#246802 Hite Bob US-CA90291 Venice
CanOpener 0.48 1
Spoon 1.49 4
Needle 0.05 100

以“#”开头的行是客户对象。其他行是 Purchase 对象。

我试图查看即将到来的字符,但我一次又一次地得到相同的字符。在这种情况下,我总是将“13”作为 s.peek() 的输出。

€编辑:谢谢@Mark Ransom。如果有人遇到同样的问题,这里是工作代码。 :)

istream& operator>>(istream& s, vector<Order>& ord) {
string c{};
bool got_customer = false;
Customer temp_customer{};
vector<Purchase>vec_purchase{};

while (s >> c) {
if (!got_customer) {
c.erase(c.begin()); //deletes first char of string
int k_nummer{};
string k_vname{};
string k_nname{};
string k_plz{};
string k_stadt{};
k_nummer = stoi(c); //string to int
s >> k_vname >> k_nname >> k_plz>>k_stadt>>ws;
k_vname += " " + k_nname;
temp_customer = Customer(k_nummer, k_vname, k_plz, k_stadt);
got_customer = true;
} else {
string p_name{};
double p_preis{};
int p_menge{};
p_name = c;
s >> p_preis>>p_menge>>ws;
vec_purchase.push_back(Purchase{p_name, p_preis, p_menge});
}

if (s.peek() == 35||s.peek() == -1 ) { //35 (in ascii) -> # , -1 -> end of txt file
ord.push_back(Order{temp_customer, vec_purchase});
temp_customer = Customer{};
vec_purchase.clear();
got_customer = false;
}
}
}

最佳答案

当您从流中读取时,输入将在第一个空白字符处停止。十进制代码为 13 的字符是 ASCII CR , 在 Windows 中出现在每一行的末尾;它被认为是空白。您需要跳过空格才能找到下一个重要 字符。您使用 std::ws 执行此操作.

s >> k_vname >> k_nname >> k_plz >> k_stadt >> std::ws;

s >> p_preis >> p_menge >> std::ws;

关于c++读取txt文件并复制到两个类istream::peek(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41476006/

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