我在Mac上遇到代码块和Xcode问题。每次我在代码块上运行代码时,我都会收到Segmentation Fault 11,当我尝试使用Xcode时,我会收到线程1:exc_bad_access(code = 1 address = 0x0xffffffff0000000a)。但是,如果我通过代码块在PC上运行此代码,它将运行。有没有人知道如何解决这个问题,所以我可以在我的Mac上运行该程序。
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
struct Book
{
string isbn;
string title;
string author;
double price;
string seller;
};
int main()
{
Book booklist[100];
ifstream infile;
ofstream outfile;
//int numBooks = 0;
int i=0;
char dummy;
outfile.open("readBooks.txt");
infile.open("usedBooks.txt");
if (infile.fail())
{
cout << "The file doesn't exist";
exit(-1);
}
else
{
//for (i=0; i<100; i++)
while (!infile.eof())
{
getline (infile, booklist[i].isbn);
getline (infile, booklist[i].title);
getline (infile, booklist[i].author);
infile >> booklist[i].price;
infile.get(dummy);
getline (infile, booklist[i].seller);
outfile << "ISBN: " << booklist[i].isbn << endl;
outfile << "Title: " << booklist[i].title << endl;
outfile << "Author: " << booklist[i].author << endl;
outfile << "Price: " << booklist[i].price << endl;
outfile << "Seller: " << booklist[i].seller << endl << endl;
i++;
}
}
}
答案 0 :(得分:2)
您的以下行导致了问题
while (!infile.eof())
因为它取决于文件的大小,但是你的数组大小是固定的(.i.e.100,你在那里存储数据)。
您应该在程序中使用 std :: vector :
std::vector<Book> booklist;
while(/*check about infile>>x instead of !infile.eof()*/) {
Book tmp;
getline (infile, tmp.isbn);
getline (infile, tmp.title);
getline (infile, tmp.author);
infile >> tmp.price;
infile.get(dummy);
getline (infile, tmp.seller);
outfile << "ISBN: " << tmp.isbn << endl;
outfile << "Title: " << tmp.title << endl;
outfile << "Author: " << tmp.author << endl;
outfile << "Price: " << tmp.price << endl;
outfile << "Seller: " << tmp.seller << endl << endl;
//Add into the vector after filling the data into the
//struct Book instance tmp
booklist.push_back(tmp);
}
修改强> 是的,我不应该检查 infile.eof(),因为这不是识别文件结尾的可靠方法。而不是这个,我们应该检查 infile&gt;&gt; x 。有关详细信息,请参阅ISOCPP常见问题链接:http://isocpp.org/wiki/faq/input-output#istream-and-eof
答案 1 :(得分:2)
Book booklist[100];
使用魔术数字是不好的做法。你确定i
在你的程序中总是少于100吗?如果没有那么你的程序可能会做一些奇怪的事您应该使用std::vector<Book> booklist;
代替。您可能还想使用向量的at()
成员函数来避免错误,将数组索引越界。
//for (i=0; i<100; i++)
while (!infile.eof())
{
在循环条件中使用.eof()
检查C ++流是almost always wrong。相反,你可能想要:
// returns true of book is successfully read, false otherwise
bool read_book(std::istream &is, Book &book) {
Book tmp;
if (getline(is, tmp.isbn) &&
getline(is, tmp.title) &&
getline(is, tmp.author) &&
is >> tmp.price)
{
is.get(dummy);
if (getline(is, tmp.seller)) {
book = tmp; // book = std::move(tmp)
return true;
}
}
return false;
}
int main() {
std::vector<Book> booklist;
// ...
Book book;
while (read_book(infile, book)) {
booklist.push_back(book);
}
// ...
}
您应该始终检查输入操作的结果,并检查C ++流上的eof()
是否进行了正确的检查。