-1
我试图完成没有太多经验CSE实验室与I/O或使用文本文件中的行。该计划的目标是根据用户反馈的词汇和定义创建词典。输出文本文件的格式应该是覆盖和追加在文本文件(C++)
条目数(如一个数字)
字
定义
字
定义
等。
在这一点上,输出读取,如果你所有的话是 “阿尔伯塔省” 和定义 “三人行”:
阿尔伯塔
三人
2Alberta
三人
2Alberta
三人
东西显然是非常错误的。下面是结果代码:如果它很混乱并且输出语句被分开,我很遗憾,我一直试图弄清楚这一点。
#include <iostream>
#include <string>
#include <fstream>
#include <stdlib.h>
using namespace std;
int main()
{
string name; // Name of writing/reading document
cout << "Please enter the path (including file name) for the dictionary you want to create: " ;
getline(cin,name); // Inputs name
fstream dicFile;
int addcount = 0; // number of times file has been added to.
int choice = 0; // Controls while loop
while (choice != 3)
{
cout << "- - - - - - - - - -" << endl;
cout << "1) Add a word to the dictionary" << endl;
cout << "2) Print Dictionary" << endl;
cout << "3) Quit" << endl;
cout << "Choose an option from the menu: ";
string choiceS;
getline(cin,choiceS);
choice = atoi(choiceS.c_str());
string wordAdd; // Stores word to be added
string defAdd; // Stores definition to be added
int size = 1; // Number of entries after the first entry
if(choice > 0 && choice < 4)
{
cout << "- - - - - - - - - -" << endl;
if(choice == 1)
{
if(addcount == 0)
{
dicFile.open(name.c_str(),ios::in|ios::out|ios::app);
cout << "Enter a word or phrase to add to the dictionary: ";
getline(cin,wordAdd);
dicFile << size;
dicFile << endl;
dicFile << wordAdd;
dicFile << endl;
cout << "Enter the definition for \"" << wordAdd << "\": ";
getline(cin,defAdd);
dicFile << defAdd << endl;
dicFile.close();
addcount++;
}
else
{
dicFile.open(name.c_str(),ios::in|ios::out|ios::app);
size = size + 1;
dicFile << size;
dicFile.close();
dicFile.open(name.c_str(),ios::in|ios::out|ios::app);
cout << "Enter a word or phrase to add to the dictionary: ";
getline(cin,wordAdd);
dicFile << wordAdd;
dicFile << endl;
cout << "Enter the definition for \"" << wordAdd << "\": ";
getline(cin,defAdd);
dicFile << defAdd << endl;
dicFile.close();
}
}
if(choice == 2)
{
if(true)
{
dicFile.open(name.c_str(),ios::in);
string readSize;
int readSizei;
getline(dicFile,readSize);
readSizei = atoi(readSize.c_str());
for(int i = 0; i < readSizei*2 + 1; i++)
{
string word;
string def;
getline(dicFile,word);
cout << word << endl;
getline(dicFile,def);
cout << def << endl;
}
dicFile.close();
}
else
{ cout << "- - - - - - - - - -" << endl;
cout << "The dictionary is empty!" << endl;
}
}
}
else
{ cout << "- - - - - - - - - -" << endl;
cout << "Invalid menu selection (number should be between 1-3)" << endl;
}
}
}
我有什么,以覆盖文本文件的第一行,但附加到文件的新定义,当我选择选项2,怎么办?相当新的I/O。谢谢你的时间。
这听起来很简单,但我该怎么做呢? – Kotsuzui
非常感谢您的时间,我会尽力。 – Kotsuzui