简体   繁体   中英

c++ writing into a file

I am writing a code to make a dictionary using avl balanced tree structure and file handling. the user enters the word and its meaning. The words are stored in the nodes of the tree and the words and their meaning in a text file. when the user enters the word and the meaning it should be stored in the file as:

word " tab " meaning

But the word and meaning are getting written on 2 different lines. Following is my code:

#include <iostream>
#include<fstream>
#include<string.h>
using namespace std;

class node                  //Create a class for node.
{  public:
char keyword[10];
char meaning[100];
node *lc;
node *rc;
int h;
friend class avl;
};

class avl                   //Create a class for avl.
{public:
node* root;
avl()
{
    root=NULL;          //Initialise root to NULL.
}
node *insert(node *root,char[],char[]);
void insert1();
int height(node *);
int bal_fac(node*);
node *LL(node*);
node *LR(node*);
node *RL(node*);
node *RR(node*);
};
void avl:: insert1()        //Insert1 function to read file contents.
{
char data[10]=" ";
char meaning[100];
cout<<endl<<"Enter word: ";
cin>>data;
int len=strlen(data);
len+=4;
char line[len];
cout<<endl<<"Enter its meaning: ";
cin.getline(meaning,100,'.');
fstream myfile;
int i;
for (i=0;i<strlen(data);i++)
{
    line[i]=data[i];
}
line[i++]='.';
line[i++]='t';
line[i++]='x';
line[i++]='t';
line[i]='\0';

myfile.open(line,ios::out); //To read from file using object myfile.
if(myfile.is_open())
{
myfile<<"data          meaning"<<endl;
myfile.close();
myfile.open(line,ios::app);
    myfile<<data<<meaning;

    root=insert(root,data,meaning);//Insert new node in tree.
    myfile.close();
}
else
    cout<<"Unable to open file"<<endl;

        }

what changes should I make?

I think it's likely that your data (the word) has an endl character in it. Double check that you're removing any whitespace (from both the word and its meaning).

edit: per stefaanv, it's the meaning that has the endl (at the beginning). When you're reading in the input with cin.getline(). Perhaps using the cin << stream might be a better option for you.

STDIN (standard input) is buffered and

cin >> i;

leaves '\\n' in the buffer. You either have to flush the buffer before reading again using getline eg:

cin.clear(); fflush(stdin);

for more look at this question How do I clear the cin buffer in C++ .

or you can use getline when reading data

cin.getline(data,10);

this way you don't have to flush the stdin buffer when you want to read the meaning.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM