试图阅读文本文件C ++

时间:2011-04-11 04:19:23

标签: c++ file text fstream

使用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();

}

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

ifstream :: operator&gt;&gt;是什么做一个单元化的char *(或者就此而言是一个initiazized char *)。我猜你想要一个字符串而不是一个char * ==现在我觉得你正在读随机记忆。

因此,要明确,请尝试替换

char* path;

string path

char* placeholder;

string placeholder;

您还需要添加:

#include <string>

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