【问题标题】:Trying to read text file C++试图读取文本文件 C++
【发布时间】:2011-04-11 04:19:22
【问题描述】:

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

}

感谢您的所有帮助!

【问题讨论】:

标签: c++ file text fstream


【解决方案1】:

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

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

char* path;

string path

char* placeholder;

string placeholder;

您还需要添加:

#include &lt;string&gt;

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

【讨论】:

  • 另外,在 Visual Studio 中运行此代码会导致堆栈溢出。有什么想法吗?
  • 和我之前说的原因一样——路径指向的随机地址必须在堆栈的某个地方,当你读到它时,你会吹走一些重要的东西。
猜你喜欢
  • 1970-01-01
  • 2016-07-23
  • 2021-03-10
  • 2015-05-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多