C++ 将名称保存在文件中
我想将几个书名保存到一个文件中,然后从文件中读取它们。像这样:C++ 将名称保存在文件中,c++,C++,我想将几个书名保存到一个文件中,然后从文件中读取它们。像这样: char name[100]; cout<<"Enter the name of the book:"; cin.getline(name,100); ofstream bookname("D:bookname.txt",ios::app); if(bookname.is_open()){ bookname<<name<<"\n"; bookname.close(); } el
char name[100];
cout<<"Enter the name of the book:";
cin.getline(name,100);
ofstream bookname("D:bookname.txt",ios::app);
if(bookname.is_open()){
bookname<<name<<"\n";
bookname.close();
}
else {
cout<<"The file does'nt open successfully!\n";
}
字符名[100];
cout我认为您的基本问题是您在输入流上使用>>,并且一次只能读取一个单词。要一次读取一行,应使用getline()。首先,不能将/n
保存到文件中,在某些情况下,这可能会导致读取文件时出现一些问题
代码中的另一件事是将名称保存为字符,并将其读取为字符串,这就是问题的原因。保存字符的方式不同于保存字符串的方式。当你写字符串时,你只需要写一行完整的句子
我想你的代码应该是这样的
写作:
string name;
cout<<"Enter the name of the book:";
getchar();
getline(cin,name);
ofstream bookname("D:bookname.txt",ios::app);
if(bookname.is_open()){
bookname<<name;
bookname.close();
}
else
cout<<"The file does'nt open successfully!\n";
}
整合您自己和您的代码。询问明确的需求以及您一直试图解决的问题。你显然不止一本书,所以这需要一个循环?图书馆的负责人输入书的名字,然后程序将它们保存到一个文本文件中。学生搜索书,我想从文件中读出来,并展示书籍。我总是希望身边有甜美的独角兽,放屁发出美妙的彩虹。清楚点,伙计!相反,选择std::getline()
。你很困惑。这与文件的“保存”方式无关,只要打开文件就知道了。事实上,整个观察结果是不合逻辑的:文本文件是字节流。文本文件如何区分“秘密”、“花园”和“秘密花园”?!问题是你从那个文件中读错了,这很奇怪,因为你在第一个代码片段中读对了。
string name;
cout<<"Enter the name of the book:";
getchar();
getline(cin,name);
ofstream bookname("D:bookname.txt",ios::app);
if(bookname.is_open()){
bookname<<name;
bookname.close();
}
else
cout<<"The file does'nt open successfully!\n";
}
string n[100];
int c=0;//the number of times you read a sentence
ifstream read("D:bookname.txt");
while(read)//keap reading from the file until you reach eof.
{
read>>n[c];
c++;
}
read.close();