Problem with calling char from function

Every time I try to use the function SaveNewCD, it doesn't write to file correctly. It writes the ~, three characters, then goes into an infinite loop.

How can I fix this. I'm stumped!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include<iostream>
#include<fstream>
using namespace std;
int SaveNewCD();
int OpenCD();
int main()
    { char ArtistName[25];
      char CDTitle[25];
      float Price;
      int MenuOption; 
      do 
        { cout<<"\nEnter 1(Add), 2 (display), or 3(exit): ";
          cin>>MenuOption; 
          if (MenuOption ==3){ break;}
          else if (MenuOption ==1)  
              {SaveNewCD();}
          else if (MenuOption ==2)
           {OpenCD();}
           else;
       
        } while (MenuOption !=3);
      system("pause");
        }  
      
int SaveNewCD()  
         { 
             char ArtistName[25];
             char CDTitle [25];
             float Price;  
               ofstream MarthyCD("MarthyCD.dat",ios::app);
              if (MarthyCD.fail()) 
                 {cout<<"\nfile Does not Exist."; 
                 exit(1);}
             else {cout<<"\nFile Exists.";
                 cout<<"\nEnter the Artist Name: "; 
                 cin.getline(ArtistName, 25);
                 cin.get();
                 cout<<"\nEnter the CD Title: "; 
                 cin.getline(CDTitle, 25);
                 cin.get();
                 cout<<"\nEnter the Price: ";
                 cin>>Price;
                 cin.get();
                 MarthyCD<<ArtistName<<'~'<<CDTitle<<'~'<<Price<<endl;
                  }}
Last edited on
Use code tags.

Have you tried running a debugger to see what the values of ArtistName, etc. are before you write them to the file?
No I have not. I'm pretty new to C++ and I don't really know how to debug well. I'm currently using bloodshed as a compiler.
An alternative to Zhuge's suggestion is to cout something in certain parts of your program to determine if it's running correctly. For instance you can write

cout << ArtistName << " " << CDTitle << "\n";

between line 43 and 44 to determine if they hold the right stuff. This is a lot more time consuming than using a debugger though and it's worth investing time learning it.
So I tried the Cout. and it came up blank. It actually appeared to take the value prior to when I want the cin

So I changed cin.getline to cin >> ArtistNAme. And it worked until I entered a number along with a word . Then I got the error.
Last edited on
I figured it out. A cin.get seemed to do the trick prior to reading the function.

Where can I be directed on how to use a debugger? thanks for the help.
Topic archived. No new replies allowed.