写入文件时出现问题

发布于 2024-11-01 14:54:52 字数 9710 浏览 4 评论 0原文

伙计们,我编写了以下代码来用 C++ 实现电话簿 我所做的是首先从包含姓名、地址和电话号码的三个文件中获取输入(您可能不会查看整个代码),只需查看底部

现在我让用户添加要在运行时添加的联系人,这些值存储在一堂课。 现在,我删除包含姓名、地址和号码的文件,并使用 ofstream 将新数据写入其中,当用户再次运行“电话簿”时将检索这些数据,

但是在程序运行一次后我无法看到文件中的任何输入,我在运行时添加了一些值。 有人可以帮助我吗? 提前致谢

    #include<iostream>//Include Header Files   
    #include<cstdlib>
    #include<fstream>
    #include<string>
    using namespace std;

    class contact{

    public:

         string name;//ALL CLASS VARIABLES ARE PUBLIC

         int phonenumber;

         string address;

         contact(){//Constructor

         name= "Noname";

         phonenumber= 0;

         address= "Noaddress";

    }


    };

    int main(){

         contact *d;

         d= new contact[200];

         string name,add;

         int choice,modchoice,k=0;//Variable for switch statement

         int phno,phno1;

         int i=0;
         int initsize=0, i1=0;//i is declared as a static int variable

         bool flag=false,flag_no_blank=false;


         //TAKE DATA FROM FILES.....
         //We create 3 files names, phone numbers, Address and then abstract the data from these files first!

         fstream f1;
         fstream f2;
         fstream f3;

         string file_input_name; 
         string file_input_address;

         int file_input_number;


         f1.open("./names");

         while(f1>>file_input_name){

              d[i].name=file_input_name;

              i++;

         }
         initsize=i;

         f2.open("./numbers");

         while(f2>>file_input_number){

              d[i1].phonenumber=file_input_number;
              i1++;

         }

         i1=0;


         f3.open("./address");

         while(f3>>file_input_address){

              d[i1].address=file_input_address;

              i1++;

         }





         cout<<"\tWelcome to the phone Directory\n";//Welcome Message
         do{    
              //do-While Loop Starts
              cout<<"Select :\n1.Add New Contact\n2.Update Existing Contact\n3.Display All Contacts\n4.Search for a Contact\n5.Delete a  Contact\n6.Exit PhoneBook\n\n\n";//Display all options


              cin>>choice;//Input Choice from user



              switch(choice){//Switch Loop Starts

              case 1:{

                   i++;//increment i so that values are now taken from the program and stored as different variables 
                   i1++;

               do{

                        cout<<"\nEnter The Name\n";

                cin>>name;

                if(name==" "){cout<<"Blank Entries are not allowed";
                                 flag_no_blank=true;

                }

               }while(flag_no_blank==true);


                   flag_no_blank=false;



               d[i].name=name;

               cout<<"\nEnter the Phone Number\n";

                   cin>>phno;

                   d[i1].phonenumber=phno;



               cout<<"\nEnter the address\n";


                   cin>>add;

                   d[i1].address=add;

               i1++;

                   i++;

                   break;//Exit Case 1 to the main menu
              }

              case 2:   {

                   cout<<"\nEnter the name\n";//Here it is assumed that no two contacts can have same contact number or address but may have the same name.

               cin>>name;

               int k=0,val;

               cout<<"\n\nSearching.........\n\n";

               for(int j=0;j<=i;j++){


                    if(d[j].name==name){

                     k++;           

                     cout<<k<<".\t"<<d[j].name<<"\t"<<d[j].phonenumber<<"\t"<<d[j].address<<"\n\n";

                     val=j;                 

                     }

                 }


                 char ch;

                 cout<<"\nTotal of "<<k<<" Entries were found....Do you wish to edit?\n";

                 string staticname;

                 staticname=d[val].name;

                 cin>>ch;

                 if(ch=='y'|| ch=='Y'){

                      cout<<"Which entry do you wish to modify ?(enter the old telephone number)\n";

                      cin>>phno;

                  for(int j=0;j<=i;j++){

                       if(d[j].phonenumber==phno && staticname==d[j].name){

                            cout<<"Do you wish to change the name?\n";

                        cin>>ch;

                            if(ch=='y'||ch=='Y'){

                             cout<<"Enter new name\n";

                         cin>>name;

                         d[j].name=name;

                        }

                        cout<<"Do you wish to change the number?\n";

                            cin>>ch;

                        if(ch=='y'||ch=='Y'){

                             cout<<"Enter the new number\n";

                         cin>>phno1;

                         d[j].phonenumber=phno1;

                         }

                                     cout<<"Do you wish to change the address?\n";

                         cin>>ch;

                         if(ch=='y'||ch=='Y'){

                              cout<<"Enter the new address\n";

                          cin>>add;

                          d[j].address=add;

                         }

                        }               

                   }

                      }

                      break;

                 }

             case 3 : {

                  cout<<"\n\tContents of PhoneBook:\n\n\tNames\tNumbers\tAddresses\n";

                  for(int t=0;t<=i;t++){

                       if(d[t].name=="Noname") continue;

                       cout<<".\t"<<d[t].name<<"\t"<<d[t].phonenumber<<"\t"<<d[t].address<<"\n";

                  }

                      cout<<"\n\n\n\n";

                  break;

                 }

             case 4:{
                  cout<<"Enter a name to search\n";

                  cin>>name;

                      cout<<"\n\nSearching.........\n\n";

                  for(int j=0;j<=i;j++){

                      if(d[j].name==name){

                       k++;         

                   cout<<k<<".\t"<<d[j].name<<"\t"<<d[j].phonenumber<<"\t"<<d[j].address<<"\n\n";

                   int val=j;                   

                  }

             }

             cout<<"\nA total of "<<k<<" contact names were found having the name"<<name;

             break;
            }
            case 6:{

                 cout<<"\n\nClosing the phonebook...Visit Again\n";

             flag=true;

                 break;

            }

            case 5: {

                 cout<<"\nEnter the contact-name\n";//Here it is assumed that no two contacts can have same contact number or address but may have the same name.

             cin>>name;

             int k=0,val;

             cout<<"\n\nSearching.........\n\n";

             for(int j=0;j<=i;j++){

                      if(d[j].name==name){
                       k++;         

                   cout<<k<<".\t"<<d[j].name<<"\t"<<d[j].phonenumber<<"\t"<<d[j].address<<"\n\n";
                                                                                      val=j;                    

                  }

             }


             char ch;

             cout<<"\nTotal of "<<k<<" Entries were found....Do you wish to delete?\n";

             if(k==0) break;

             string staticname;

             staticname=d[val].name;

             cin>>ch;

             if(ch=='y'|| ch=='Y'){

                  cout<<"Which entry do you wish to delete ?(enter the old telephone number)\n";

                  cin>>phno;

                  for(int j=0;j<=i;j++){

                       if(d[j].phonenumber==phno && staticname==d[j].name){

                                val=j;                  

                   }

                      }

                      for(int j=val;j<=i-1;j++){

                           d[j].name=d[j+1].name;


                           d[j].phonenumber=d[j+1].phonenumber;


                           d[j].address=d[j+1].address;

                      }

                      d[i].name="Noname";


                      d[i].phonenumber=0;


                      d[i].address="Noaddress";

                 }


                 break;

            }

       }
  }


  while(flag==false);

  std::ofstream f4("./names");

  f4.close();

  std::ofstream f5("./numbers");

  f5.close();

  std::ofstream f6("./address");

  f6.close();

  f1.close();

  f2.close();

  f3.close();

  ofstream f7,f8,f9;

  f7.open("names");

  f8.open("numbers");

  f9.open("address");
  int y=0;

  string w;

  w=d[0].name;

  while(f7<<w && y<=i){

  if(w=="Noname") y++; continue;

  y++;

  w=d[y].name;

  }

  y=0;
  int v;
  v=d[0].phonenumber;
  while(f8<<v && y<=i){
       if(v==0){y++; continue;}
       y++;
       v=d[y].phonenumber;
  }

  y=0;

  string u;
  u=d[0].address;

  while(f9<<u && y<=i ){

       if(u=="Noaddress"){

            continue;
            y++;
       }

       y++;

       u=d[y].address;

  }

  return 0;

  }     

Guys I wrote the following code for implementing a phonebook in c++
What I am doing is first take input from three files containing names, address and phone number(u may not look at the entire code) just look at the bottom

Now I give user to add contacts to add during runtime and these values are stored in a class.
Now I erase the files containing names, address and numbers and write new data into them using ofstream which will be retrieved when user again runs the "phonebook"

however i am not able to see any input into the files after program has run once and I added a few values during the runtime.
Can someone help me?
Thanks in advance

    #include<iostream>//Include Header Files   
    #include<cstdlib>
    #include<fstream>
    #include<string>
    using namespace std;

    class contact{

    public:

         string name;//ALL CLASS VARIABLES ARE PUBLIC

         int phonenumber;

         string address;

         contact(){//Constructor

         name= "Noname";

         phonenumber= 0;

         address= "Noaddress";

    }


    };

    int main(){

         contact *d;

         d= new contact[200];

         string name,add;

         int choice,modchoice,k=0;//Variable for switch statement

         int phno,phno1;

         int i=0;
         int initsize=0, i1=0;//i is declared as a static int variable

         bool flag=false,flag_no_blank=false;


         //TAKE DATA FROM FILES.....
         //We create 3 files names, phone numbers, Address and then abstract the data from these files first!

         fstream f1;
         fstream f2;
         fstream f3;

         string file_input_name; 
         string file_input_address;

         int file_input_number;


         f1.open("./names");

         while(f1>>file_input_name){

              d[i].name=file_input_name;

              i++;

         }
         initsize=i;

         f2.open("./numbers");

         while(f2>>file_input_number){

              d[i1].phonenumber=file_input_number;
              i1++;

         }

         i1=0;


         f3.open("./address");

         while(f3>>file_input_address){

              d[i1].address=file_input_address;

              i1++;

         }





         cout<<"\tWelcome to the phone Directory\n";//Welcome Message
         do{    
              //do-While Loop Starts
              cout<<"Select :\n1.Add New Contact\n2.Update Existing Contact\n3.Display All Contacts\n4.Search for a Contact\n5.Delete a  Contact\n6.Exit PhoneBook\n\n\n";//Display all options


              cin>>choice;//Input Choice from user



              switch(choice){//Switch Loop Starts

              case 1:{

                   i++;//increment i so that values are now taken from the program and stored as different variables 
                   i1++;

               do{

                        cout<<"\nEnter The Name\n";

                cin>>name;

                if(name==" "){cout<<"Blank Entries are not allowed";
                                 flag_no_blank=true;

                }

               }while(flag_no_blank==true);


                   flag_no_blank=false;



               d[i].name=name;

               cout<<"\nEnter the Phone Number\n";

                   cin>>phno;

                   d[i1].phonenumber=phno;



               cout<<"\nEnter the address\n";


                   cin>>add;

                   d[i1].address=add;

               i1++;

                   i++;

                   break;//Exit Case 1 to the main menu
              }

              case 2:   {

                   cout<<"\nEnter the name\n";//Here it is assumed that no two contacts can have same contact number or address but may have the same name.

               cin>>name;

               int k=0,val;

               cout<<"\n\nSearching.........\n\n";

               for(int j=0;j<=i;j++){


                    if(d[j].name==name){

                     k++;           

                     cout<<k<<".\t"<<d[j].name<<"\t"<<d[j].phonenumber<<"\t"<<d[j].address<<"\n\n";

                     val=j;                 

                     }

                 }


                 char ch;

                 cout<<"\nTotal of "<<k<<" Entries were found....Do you wish to edit?\n";

                 string staticname;

                 staticname=d[val].name;

                 cin>>ch;

                 if(ch=='y'|| ch=='Y'){

                      cout<<"Which entry do you wish to modify ?(enter the old telephone number)\n";

                      cin>>phno;

                  for(int j=0;j<=i;j++){

                       if(d[j].phonenumber==phno && staticname==d[j].name){

                            cout<<"Do you wish to change the name?\n";

                        cin>>ch;

                            if(ch=='y'||ch=='Y'){

                             cout<<"Enter new name\n";

                         cin>>name;

                         d[j].name=name;

                        }

                        cout<<"Do you wish to change the number?\n";

                            cin>>ch;

                        if(ch=='y'||ch=='Y'){

                             cout<<"Enter the new number\n";

                         cin>>phno1;

                         d[j].phonenumber=phno1;

                         }

                                     cout<<"Do you wish to change the address?\n";

                         cin>>ch;

                         if(ch=='y'||ch=='Y'){

                              cout<<"Enter the new address\n";

                          cin>>add;

                          d[j].address=add;

                         }

                        }               

                   }

                      }

                      break;

                 }

             case 3 : {

                  cout<<"\n\tContents of PhoneBook:\n\n\tNames\tNumbers\tAddresses\n";

                  for(int t=0;t<=i;t++){

                       if(d[t].name=="Noname") continue;

                       cout<<".\t"<<d[t].name<<"\t"<<d[t].phonenumber<<"\t"<<d[t].address<<"\n";

                  }

                      cout<<"\n\n\n\n";

                  break;

                 }

             case 4:{
                  cout<<"Enter a name to search\n";

                  cin>>name;

                      cout<<"\n\nSearching.........\n\n";

                  for(int j=0;j<=i;j++){

                      if(d[j].name==name){

                       k++;         

                   cout<<k<<".\t"<<d[j].name<<"\t"<<d[j].phonenumber<<"\t"<<d[j].address<<"\n\n";

                   int val=j;                   

                  }

             }

             cout<<"\nA total of "<<k<<" contact names were found having the name"<<name;

             break;
            }
            case 6:{

                 cout<<"\n\nClosing the phonebook...Visit Again\n";

             flag=true;

                 break;

            }

            case 5: {

                 cout<<"\nEnter the contact-name\n";//Here it is assumed that no two contacts can have same contact number or address but may have the same name.

             cin>>name;

             int k=0,val;

             cout<<"\n\nSearching.........\n\n";

             for(int j=0;j<=i;j++){

                      if(d[j].name==name){
                       k++;         

                   cout<<k<<".\t"<<d[j].name<<"\t"<<d[j].phonenumber<<"\t"<<d[j].address<<"\n\n";
                                                                                      val=j;                    

                  }

             }


             char ch;

             cout<<"\nTotal of "<<k<<" Entries were found....Do you wish to delete?\n";

             if(k==0) break;

             string staticname;

             staticname=d[val].name;

             cin>>ch;

             if(ch=='y'|| ch=='Y'){

                  cout<<"Which entry do you wish to delete ?(enter the old telephone number)\n";

                  cin>>phno;

                  for(int j=0;j<=i;j++){

                       if(d[j].phonenumber==phno && staticname==d[j].name){

                                val=j;                  

                   }

                      }

                      for(int j=val;j<=i-1;j++){

                           d[j].name=d[j+1].name;


                           d[j].phonenumber=d[j+1].phonenumber;


                           d[j].address=d[j+1].address;

                      }

                      d[i].name="Noname";


                      d[i].phonenumber=0;


                      d[i].address="Noaddress";

                 }


                 break;

            }

       }
  }


  while(flag==false);

  std::ofstream f4("./names");

  f4.close();

  std::ofstream f5("./numbers");

  f5.close();

  std::ofstream f6("./address");

  f6.close();

  f1.close();

  f2.close();

  f3.close();

  ofstream f7,f8,f9;

  f7.open("names");

  f8.open("numbers");

  f9.open("address");
  int y=0;

  string w;

  w=d[0].name;

  while(f7<<w && y<=i){

  if(w=="Noname") y++; continue;

  y++;

  w=d[y].name;

  }

  y=0;
  int v;
  v=d[0].phonenumber;
  while(f8<<v && y<=i){
       if(v==0){y++; continue;}
       y++;
       v=d[y].phonenumber;
  }

  y=0;

  string u;
  u=d[0].address;

  while(f9<<u && y<=i ){

       if(u=="Noaddress"){

            continue;
            y++;
       }

       y++;

       u=d[y].address;

  }

  return 0;

  }     

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

北恋 2024-11-08 14:54:53

顺便提一句。

while(f7<<w && y<=i){
    if(w=="Noname") 
        y++;          // <- proper indention is king
    continue;
    y++;              // <- never reached
    w=d[y].name;      // <- never reached
}

while(f8<<v && y<=i){
    if(v==0) {
        y++; 
        continue;
    }
    y++;
    v=d[y].phonenumber;
}

while(f9<<u && y<=i ){
    if(u=="Noaddress") {
        continue;
        y++;         // <- never reached
    }
    y++;
    u=d[y].address;
}

btw.

while(f7<<w && y<=i){
    if(w=="Noname") 
        y++;          // <- proper indention is king
    continue;
    y++;              // <- never reached
    w=d[y].name;      // <- never reached
}

while(f8<<v && y<=i){
    if(v==0) {
        y++; 
        continue;
    }
    y++;
    v=d[y].phonenumber;
}

while(f9<<u && y<=i ){
    if(u=="Noaddress") {
        continue;
        y++;         // <- never reached
    }
    y++;
    u=d[y].address;
}
水溶 2024-11-08 14:54:53

我明白你为什么感到沮丧,编码员。这是令人沮丧的代码。

while(flag==false) (根据乔纳森的评论,这并不像看起来那么糟糕。它仍然很糟糕,甚至很难从其他垃圾中判断出真正的垃圾混乱...:)

WTF?只是不要按“6”退出,否则你会白白烧掉你的CPU

无论如何,它仍然在消耗 100% 的 CPU 并以危险的速度填充 /tmp。我想,它不被称为无限循环(因为一旦文件系统满了它就会退出)。感谢上帝,/tmp 在 tmpfs 上(大小 4g),我有 8g 的内存可用:)

将名称、数字和地址存储在单独的文件中......嗯可能是个好主意。

一次测试运行中,我让它写入 3.7G 到地址:) ("NoaddressNoaddressNoaddressNoaddressNo....") 很甜蜜,让它崩溃,因为加载时,接收地址的缓冲区(显然称为 d)正好是200条记录。

坦率地说,这段代码应该移至 TheDailyWTF。快点快点!

此代码无法修复。时期

I can see why you are frustrated, coder. This is frustrating code.

while(flag==false) (as per Jonathans comment this isn't as blatantly bad as it appeared. It still is bad that it is even hard to judge the real junk from the rest of the mess... :)

WTF? Just don't hit '6' to exit, or you will be frying your CPU for free

It was still burning 100% of CPU and filling /tmp at a hazardous pace anyway. I guess, it is not called an infinite loop (because it exits as soon as the filesystem is full). Thank god, /tmp is on tmpfs (size 4g) and I have 8g of ram available :)

Storing the names, numbers and addresses in separate files... hm probably a good idea.

One test run I had it writing 3.7G to address :) ("NoaddressNoaddressNoaddressNoaddressNo....") Just sweet to make it crash because on load, the buffer to receive address in (obviously called d) is precisely 200 records.

Frankly this code should move to TheDailyWTF. Pronto Pronto!

This code can not be fixed. Period

鹤舞 2024-11-08 14:54:53

这个程序有很多问题。让我们首先尝试修复一些问题,然后在此基础上进行构建。

首先,名字是什么样的?它是否有空格,例如“Fred Jones”,或者可能有逗号,例如“Jones,Fred”。也许很多像“陈光生”这样的部分。

如果允许空格,则无法用“<<”读入。也许您可以在每一行输入一个名称并使用 getline() 读取它。

尝试编写一个仅读取名称并存储它们的小程序。您可以使用编辑器创建该文件。一旦可行,我们就可以在此基础上继续发展。

There are a multitude of things wrong with this program. Lets try to fix a few for a start and then build on that.

Firstly, what does a name look like? Does it have a space, like "Fred Jones" or maybe a comma like "Jones,Fred". Maybe many parts like "Chan Kong Sang".

If you permit spaces, then you can't read it in with "<<". Maybe you can put one name per line and read it in with getline().

Try writing a small program that just reads in names and stores them. You can create the file using an editor. Once that works, we can build on it.

不必你懂 2024-11-08 14:54:52

C++ 是否自动处理 I/O 错误?心理上?如果没有,那么您的错误返回处理程序在哪里?只是问一下。

编辑回应OP的评论:是的,我明白,但通常如果数据没有写入文件,文件系统会返回一个错误代码,试图告诉您为什么没有写它。但您决定忽略文件系统所说的内容。我希望能给您一个提示的问题应该是:

“如果您不检查文件写入调用返回代码,那么您将在尝试调试程序时经历一段漫长的旅程。请检查这些错误返回代码并告诉我们它们是什么,毕竟这是标准的和必需的编程实践,如果您不遵循标准的、必需的实践,那么您就只能这样做了。希望是咨询街角的吉普赛算命先生。

“那么:每个文件 I/O 调用返回的代码是什么?

尝试一下并告诉我们更多信息:我需要这个。” 。

Does C++ handle I/O errors automatically? Psychically? If not, then where are your error-return handlers? Just askin'.

EDIT in response to the OP's comment: Yes, I understand, but ordinarily if data is not being written to the file, the file system returns an error code that tries to tell you why it was not written. But you decided to ignore what the file system had to say. My question, which I'd hoped would give you a hint, should have been:

"If you don't check the file-write-call return codes, you will have a good, long hike trying to debug your program. Please check those error return codes and tell us what they are. This is standard and required programming practice, after all, and if you don't follow standard, required practice then your only hope is to consult the gypsy fortune-teller on the corner.

"SO: what are the codes being returned from each and every file-I/O call?"

Try that and tell us more. And thanks for the downvote: I needed that.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文