gpt4 book ai didi

c++ - 试图读取文本文件 C++

转载 作者:行者123 更新时间:2023-11-28 08:21:39 24 4
gpt4 key购买 nike

使用 Dev C++,我们试图让代码一次读取一行并将其存储在数组中。我们似乎没有收到任何官方错误,但是屏幕上会弹出一个窗口框来寻找错误的解决方案?

#include <iostream>
#include <fstream>
#include "AddressBook.h"

const int ADDR_BOOK_SZ = 1000;

void AddNewAddressBook(AddressBook* current);
void PrintAddresses(AddressBook* addrBook);

using namespace std;
int main(int argc, char** argv) {
AddressBook addrBook[ADDR_BOOK_SZ];
AddressBook* current;
char* path;
ifstream file;
char* placeholder;
bool running = true;
char entered;
while(running) {
//print directions
cout << "a) Open an address book file\n"
<< "b) Add a new address book entry\n"
<< "c) Print the contents of current address book\n"
<< "d) Quit" << endl;

//get the user's command
cin >> entered;

//set pointer to the current addressbook
current = addrBook + AddressBook::entryCnt_;

if(entered == 'a') {
cout << "Please enter the file path for the address book file: " << '\n';
cin >> path;
file.open(path);
int i = 0;
while(!file.eof()){

//getline(placeholder, 100);
file >> placeholder;
addrBook[i].SetFirstName(placeholder);
file >> placeholder;
addrBook[i].SetFirstName(placeholder);
file >> placeholder;
addrBook[i].SetStreetNum((int)placeholder);
file >> placeholder;
addrBook[i].SetStreetName(placeholder);
file >> placeholder;
addrBook[i].SetCity(placeholder);
file >> placeholder;
addrBook[i].SetState(placeholder);
file >> placeholder;
addrBook[i].SetZipCode((int)placeholder);
i++;
}
}
else if(entered == 'b') {
current->AddEntryFromConsole();

}
else if(entered == 'c') {
for(int i = 0; i < AddressBook::entryCnt_; i++) {
addrBook[i].PrintToConsole();
}
}
else if(entered == 'd') {
return 0;
}
else {
cout << "Wrong input entered. Try again." << endl;
}
}
file.close();

感谢您的所有帮助!

最佳答案

ifstream::operator>> 对未初始化的 char*(或就此而言已初始化的 char*)做了什么。我猜你现在想要一个字符串而不是一个 char*==,我想你正在读入随机内存。

所以,为了清楚起见,尝试替换

char* path;

string path

char* placeholder;

string placeholder;

您还需要添加:

#include <string>

请注意,这只是基于快速代码审查。

关于c++ - 试图读取文本文件 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5616695/

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