Mysterious Error: Can You See Why?

  • Thread starter yungman
  • Start date
  • Tags
    Error
In summary: I think this should be the case, since it is a compile error, rather than linking errorWarnings - obj file generatedError - no obj file generatedAnd you are right.Checking the line number and error code can lead to a solution.
  • #1
yungman
5,718
241
I encountered a strange error. I have 2 EXACTLY same code in this program, I just use /* */ to disable one or the other. The bottom one works, the top one giving me error. I literally copied the content inside main() from the bottom to the top, still, the top one fails and bottom works.
C++:
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;

main()
{
    fstream    dataFile;
    dataFile.open("C:\\Users\\alanr\\Desktop\\C++ exercise\
\\Gaddis\\inout files\\demofile.txt", ios::out | ios::app);
    dataFile << " Lucky " << " Chicky\n\n" << " Slave " << " Rooster\n\n";
    dataFile.close();
    return 0;
}
/*#include <iostream>
#include <fstream>
#include <iomanip>

using namespace std;

int main()
{
    fstream    dataFile;
    dataFile.open("C:\\Users\\alanr\\Desktop\\C++ exercise\
\\Gaddis\\inout files\\demofile.txt", ios::out|ios::app);
    dataFile << " Lucky " << " Chicky\n\n" << " Slave " << " Rooster\n\n";
    dataFile.close();

    return 0;
}*/

If I missed anything, I must be really blind. Like I said, I copied the content inside main() from bottom to the top, still have problem.

The error is :
Compile error Listing 7.2.jpg

And when I choose run anyway, the error is:
Compile error Listing 7.3.jpg


I did closed the VS and start over, also, I clean Build solution every time also. Also, I printed the code out and compared word by word. Can you see why?

thanks
 
Last edited:
Technology news on Phys.org
  • #2
They are not exactly the same... :wink:
 
  • Like
Likes sysprog
  • #3
berkeman said:
They are not exactly the same... :wink:
The content is the same. I copied the lines inside main() from the bottom to the top except return0;

You can see line 8 to line 12 is the copy from the bottom line 23 to 27.
 
  • #4
yungman said:
The content is the same. I copied the lines inside main() from the bottom to the top except return0;

You can see line 8 to line 12 is the copy from the bottom line 23 to 27.

main()
int main()

I don't know if that's the source of the error, but it appears that it was not a true copy/paste...
 
  • Like
Likes .Scott, jim mcnamara, sysprog and 1 other person
  • #5
berkeman said:
main()
int main()

I don't know if that's the source of the error, but it appears that it was not a true copy/paste...
My god, I only look at the inside content! Thank you. I wasted an afternoon, comparing word by word inside main!

Funny, I did that quite a few times, the compiler always flag me if I forgot "int" before main. It didn't this time. I went back and look at the program, it does not have red wiggle line under that. I know because it happened many times before and it will show the error so I know to put it in.

Thanks
 
  • Like
Likes sysprog and berkeman
  • #6
yungman said:
I wasted an afternoon, comparing word by word inside main!
Look at the error the compiler gave you -- it says the problem is on line 7. You can also double click on the error code, C4430, which will take you to a doc page for that error. No guarantee that it will be all that helpful. Several of the examples you've posted had compile-time errors. You could have saved yourself a lot of time by looking at the information that is shown in the error window.

berkeman said:
main()
int main()

I don't know if that's the source of the error, but it appears that it was not a true copy/paste...
It is indeed the source of the error.
Edited to add "not" -
Also, if the compiler generated an error, as opposed to a warning, I'm pretty sure that an .exe file was not generated. So I'm not clear why you would even have been able to run the program.
 
Last edited:
  • Like
Likes berkeman and sysprog
  • #7
Mark44 said:
Look at the error the compiler gave you -- it says the problem is on line 7. You can also double click on the error code, C4430, which will take you to a doc page for that error. No guarantee that it will be all that helpful. Several of the examples you've posted had compile-time errors. You could have saved yourself a lot of time by looking at the information that is shown in the error window.

It is indeed the source of the error.

Also, if the compiler generated an error, as opposed to a warning, I'm pretty sure that an .exe file was generated. So I'm not clear why you would even have been able to run the program.
Didi you mean to say that the .exe file would not be generated? (unless it's a debug version) why would an object file be created and then linked into "an .exe file" if the compiler reported an error? I think that you're better at this stuff than I am, @Mark44; would you please clarify this?
 
  • #8
Mark44 said:
Also, if the compiler generated an error, as opposed to a warning, I'm pretty sure that an .exe file was generated. So I'm not clear why you would even have been able to run the program.
I think this should be the case, since it is a compile error, rather than linking error
Warnings - obj file generated
Error - no obj file generated

And you are right.
Checking the line number and error code can lead to a solution.
Yet, the actual compiler error that is listed by line number can be from some other problem with the code in another line number, in this situation just nearby in line 6. At other times the problem code can be several lines away, which can be frustrating to locate.
 
  • #9
256bits said:
I think this should be the case, since it is a compile error, rather than linking error
Warnings - obj file generated
Error - no obj file generated

And you are right.
Checking the line number and error code can lead to a solution.
Yet, the actual compiler error that is listed by line number can be from some other problem with the code in another line number, in this situation just nearby in line 6. At other times the problem code can be several lines away, which can be frustrating to locate.
If it's an error (without debug file creation turned on), so that no object file is stored, how does the linker then link the (nonexistent) object file into the .exe file?
 
  • #10
sysprog said:
Didi you mean to say that the .exe file would not be generated? (unless it's a debug version) why would an object file be created and then linked into "an .exe file" if the compiler reported an error? I think that you're better at this stuff than I am, @Mark44; would you please clarify this?
Yes, that's exactly what I meant but somehow omitted "not". I have edited my earlier post, but not what @sysprog copied. Also, providing there are no compile or link errors, an .exe is generated whether the program is in debug mode or release mode. You can run either of them from a command prompt window separate from the VS IDE.
@yungman's statement confuses me:
yungman said:
And when I choose run anyway, the error is:
I don't see how he could run the code if a compiler error was produced, for precisely the reason you mentioned.
 
  • Like
Likes 256bits and sysprog
  • #11
256bits said:
I think this should be the case, since it is a compile error, rather than linking error
Warnings - obj file generated
Error - no obj file generated
Sorry for any confusion -- I meant that with compile errors, and .exe would not be generated, but somehow omitted that crucial word. I have edited my earlier post.
256bits said:
Checking the line number and error code can lead to a solution.
Yet, the actual compiler error that is listed by line number can be from some other problem with the code in another line number,
Right, but the most obvious place to start looking is at the line that was listed.
 
  • Like
Likes 256bits and sysprog
  • #12
Mark44 said:
Also, providing there are no compile or link errors, an .exe is generated whether the program is in debug mode or release mode.
Yep. I was right. You do know this stuff better than I do. :wink:
 
  • #13
Mark44 said:
@yungman's statement confuses me:
I don't see how he could run the code if a compiler error was produced, for precisely the reason you mentioned.
I think that sufficiency of version control may be at issue.
 
  • #14
yungman said:
I don't want to say the book is wrong, but I find it fishy on line 18.

I think that the book's line 11:
bool openFileIn(fstream &, char *);
is not incompatible with the book's line 18:
if (!openFileIn(dataFile,"demofile.txt"))

It seems to me that the book's line 18 is checking whether it is not the case that the text file is present and open.
 
Last edited:
  • #15
sysprog said:
If it's an error (without debug file creation turned on), so that no object file is stored, how does the linker then link the (nonexistent) object file into the .exe file?
Doesn't an error mean that the code is not fit for compilation?

Debug would be to see where your exe file is giving incorrect results ( example - maybe you expect it to print out a 6 and the program prints out an 8 instead ) when running.
 
  • Like
Likes sysprog
  • #16
sysprog said:
Yep. I was right. You do know this stuff better than I do. :wink:
Of course you are right.
@Mark44 gives fantastic answers regarding coding.
 
  • Like
Likes sysprog
  • #17
256bits said:
Doesn't an error mean that the code is not fit for compilation?
A compile error means that no .obj file is created. A link error means that an .obj file was created, but an .exe file could not be created.
256bits said:
Debug would be to see where your exe file is giving incorrect results ( example - maybe you expect it to print out a 6 and the program prints out an 8 instead ) when running.
Both debug mode and release mode create .exe files, provided there were no compile or link errors. Debug mode causes extra instructions to be inserted so that you can single-step through the code in the debugger - that's my understanding anyway.
 
  • Like
Likes sysprog and 256bits
  • #18
sysprog said:
I think that the book's line 11:
bool openFileIn(fstream &, char *);
is not incompatible with the book's line 18:
if (!openFileIn(dataFile,"demofile.txt"))

It seems to me that the book's line 18 is checking whether it is not the case that the text file is present and open.
Sorry, I deleted the post as I want to do more research on line and check other books. But I still cannot get the answer. I am going to post this again.

I don't follow what you said, "line 11 is not incompatible with line 18", do you mean they are compatible as "not incompatible"?
 
  • #19
I have a new question, This is straight out of the book and I spot something that is very questionable. It is on Page 661 and 662 of this book, Program 12.5. This is the link of the Gaddis book I am using. You can see in page 661, there should be a videonote...that I don't have. So I might be missing something.
https://cplusplushelp.weebly.com/uploads/2/5/6/5/25655197/0136022537.pdf

My question is on line 18. if(!openFileIn(dataFile, "demofile.txt")). If you look at line 11 bool openFileIn(fstream&, char*); The second argument is a char pointer. That doesn't match line 18.

I typed it in VS, it did flag me even before running the compiler as it should. This is my code that I typed in just in case you want to take it out to try it. My eyes is not that good, I checked, it should be the same as in the book EXCEPT on some '\n' in the cout statements AND I skip all the comments. I like to have more space between lines.

I also look into other textbooks I have and went online. I cannot find the answer.

C++:
//12.5 fstream pass by reference to function
#include <iostream>
#include <fstream>
using namespace std;

const int MAX_LINE_SIZE = 81;
bool openFileIn(fstream&, char*);
void showContents(fstream&);

int main()
{
    fstream dataFile;
    if (!openFileIn(dataFile, "demofile.txt"))
    {
        cout << " Fileopen error! \n\n";
        return 0;
    }
    cout << " File opened successfully.\n\n";
    cout << " Now reading data from file.\n\n";
    showContents(dataFile);
    cout << " done.\n\n";
    return 0;
}
bool openFileIn(fstream& file, char* name)
{
    file.open(name, ios::in);
    if (file.fail())
        return false;
    else
        return true;
}
void showContents(fstream& file)
{
    char line[MAX_LINE_SIZE];
    while(file >> line)
    {
        cout << line << endl;
    }
}

I don't want to say the book is wrong, but I find it fishy on line 18. I am going to try writing the program on my own, I am not sure you need a pointer for this. All they want is to create the file in the function openFileIn and return the file name.

Thanks
 
Last edited:
  • #20
Mark44 said:
A compile error means that no .obj file is created. A link error means that an .obj file was created, but an .exe file could not be created.
Yes that is what I meant for a compiler error - the code does not compile ".
I hope it is clear now for everyone.
 
  • #21
This is my version of passing fstream to function, open and read content.
C++:
//12.5 fstream pass by reference to function
#include <iostream>
#include <fstream>
using namespace std;

const int MAX_LINE_SIZE = 81;
bool openFileIn(fstream&);
void showContents(fstream&);

int main()
{
    ofstream outFile;
    outFile.open("demoFile.txt");
    outFile << "This is a test.\n\nAnother test";
    outFile.close();
    fstream dataFile;
    char name[81];
    if (!openFileIn(dataFile))
    {
        cout << " Fileopen error! \n\n";
        return 0;
    }
    cout << " File opened successfully.\n\n";
    cout << " Now reading data from file.\n\n";
    showContents(dataFile);
    dataFile.close();
    cout << " done.\n\n";
    return 0;
}
bool openFileIn(fstream& file )
{

    file.open("demofile.txt", ios::in);
    if (file.fail())
        return false;
    else
        return true;
}
void showContents(fstream& file)
{
    char line[MAX_LINE_SIZE];
    while (file >> line)
    {
        cout << line << " ";
    }
    cout << "\n\n";
}

I have not double check my work, but it works, I don't even need the second argument passing to function.
I added few lines in the beginning of main to create the file "demofile.txt" so I can read back from the program. It's NOT even hard to code! Like 15 minutes to fix the original code.

If this looks ok to you guys, I am going to move on. I want to finish this book. Between the stupid mistake I made in the "int main()" and this, my whole day yesterday was a total waste.

Thanks
 
  • Like
Likes sysprog
  • #22
Regarding your post #19:
yungman said:
I don't want to say the book is wrong, but I find it fishy on line 18.
Line 18 is a cout statement. Do you mean line 13?
yungman said:
My question is on line 18. if(!openFileIn(dataFile, "demofile.txt")). If you look at line 11 bool openFileIn(fstream&, char*); The second argument is a char pointer. That doesn't match line 18.
Again, this is line 13, and the prototype for openFileIn() is on line 7, not line 11.

yungman said:
I am not sure you need a pointer for this. All they want is to create the file in the function openFileIn and return the file name.
Yes, the second argument needs to be a pointer if the argument is a C-string. The parameter is of type char *; the actual argument, "demofile.txt", is of type const char *. There is a bit of type coercion going on here. You could just as well declared the function this way: bool openFileIn(fstream&, const char *); .

Also, your openFileIn() function does not return the file name -- it returns a bool.

Regarding your post #21, your new version of openFileIn() is not as good as the previous version, since the filename is hardcoded in the body of the function. The previous version allows the filename to be passed to the function, so the program could conceivably ask the user to enter the filename at run time.

yungman said:
If this looks ok to you guys, I am going to move on. I want to finish this book.
Before moving on, I would advise that you go back and work with pointers some more. There is a fair amount that you don't understand; namely, the type of a string literal (e.g., "demofile.txt"). Several posts in this thread indicate that you don't have a clear understanding in this area.
 
  • Like
Likes yungman
  • #23
Mark44 said:
Regarding your post #19:
Line 18 is a cout statement. Do you mean line 13?
Again, this is line 13, and the prototype for openFileIn() is on line 7, not line 11.

Yes, the second argument needs to be a pointer if the argument is a C-string. The parameter is of type char *; the actual argument, "demofile.txt", is of type const char *. There is a bit of type coercion going on here. You could just as well declared the function this way: bool openFileIn(fstream&, const char *); .

Also, your openFileIn() function does not return the file name -- it returns a bool.

.....
I still need to read the rest of your comments, the line number is STRAIGHT from the book, not the code I posted. I don't trust my copy 100%, this is too important, I was talking about page 661 in the book. I gave the link to the book in my post, just click and go to page 661.

Thanks
 
  • #24
yungman said:
My question is on line 18. if(!openFileIn(dataFile, "demofile.txt")). If you look at line 11 bool openFileIn(fstream&, char*); The second argument is a char pointer. That doesn't match line 18.
The version of C++ that Gaddis used apparently accepts literal strings (e.g. "demofile.txt") as compatible with char*. The compiler allocates a chunk of memory to contain the string, and generates a pointer to pass to the function.

In its default mode, my compiler compiles this program, but generates a warning for the if-statement: conversion from string literal to 'char *' is deprecated.

When I tell my compiler to use the C++11 standard, it generates an error: ISO C++11 does not allow conversion from string literal to 'char *'.

This is because a function can modify a pointer that is passed to it as char*, which shouldn't make sense for a string literal. OpenFileIn() doesn't actually modify the pointer, but in principle it could, which is what matters. I can remove the warning and error messages by making that argument const char*:

C++:
// prototype line before main()
bool openFileIn(fstream&, const char*);
// beginning of the actual function
bool openFileIn(fstream& file, const char* name)
 
  • #25
yungman said:
I still need to read the rest of your comments, the line number is STRAIGHT from the book, not the code I posted.
When you post code here, the lines are numbered. Please don't expect any of us to open the link to the book, and pore through it to find the page to see which line you're talking about.
 
  • Like
Likes Tom.G and sysprog
  • #26
Mark44 said:
When you post code here, the lines are numbered. Please don't expect any of us to open the link to the book, and pore through it to find the page to see which line you're talking about.
I link the book because I don't want to miss interpreted the book, it's the book I question. I did say the code is only if anyone want to try it.
 
  • #27
yungman said:
I link the book because I don't want to miss interpreted the book, it's the book I question. I did say the code is only if anyone want to try it.
That's fine, but if you post code and it shows line numbers, those are the line numbers you should talk about.
 
  • Like
Likes Vanadium 50 and sysprog
  • #28
You can eliminate the separate function that opens the file and tests whether the opening succeeded by using the following technique:

C++:
//12.5 fstream pass by reference to function
//Modification: opens the file when the fstream is declared,
//so we can more easily test whether it was successful.
#include <iostream>
#include <fstream>
using namespace std;

const int MAX_LINE_SIZE = 81;
void showContents(fstream&);

int main()
{
// Declares the fstream variable and initializes it by opening the file.
    fstream dataFile ("demofile.txt"); 
// If you use an fstream variable as if it were a bool, it evaluates as true or false
// depending on whether the previous operation on it succeeded.
    if (!dataFile)
    {
        cout << " Fileopen error! \n\n";
        return 0;
    }
    cout << " File opened successfully.\n\n";
    cout << " Now reading data from file.\n\n";
    showContents(dataFile);
    cout << " done.\n\n";
    return 0;
}

void showContents(fstream& file)
{
    char line[MAX_LINE_SIZE];
    while(file >> line)
    {
        cout << line << endl;
    }
}
 
  • Like
Likes sysprog
  • #29
Mark44 said:
When you post code here, the lines are numbered. Please don't expect any of us to open the link to the book, and pore through it to find the page to see which line you're talking about.
Yes ##-## I at first thought that the line numbers were in reference to the code posted here, and misinterpreted because of that, and later edited my post accordingly ##-## I think that it's better to distinguish explicitly what's being referenced.
 
  • #30
Note this program reads one word at a time, not one line at a time. If there are blank spaces on a line (i.e. multiple words), it writes each word on a separate line. To read and write each line intact, use getline(), and preferably std::string so you don't have to worry about how long the lines might be. :cool:

C++:
//12.5 fstream pass by reference to function
//Modification: opens the file when the fstream is declared,
//so we can more easily test whether it was successful.
//Modification #2: use getline() for input so we can read
//spaces, too.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

void showContents(fstream&);

int main()
{
    fstream dataFile ("demofile.txt");
    if (!dataFile)
    {
        cout << " Fileopen error! \n\n";
        return 0;
    }
    cout << " File opened successfully.\n\n";
    cout << " Now reading data from file.\n\n";
    showContents(dataFile);
    cout << " done.\n\n";
    return 0;
}

void showContents(fstream& file)
{
    string line;
    while (getline (file, line))
    {
        cout << line << endl;
    }
}
 
  • Like
Likes sysprog
  • #31
Mark44 said:
Regarding your post #19:
Line 18 is a cout statement. Do you mean line 13?
Again, this is line 13, and the prototype for openFileIn() is on line 7, not line 11.

Yes, the second argument needs to be a pointer if the argument is a C-string. The parameter is of type char *; the actual argument, "demofile.txt", is of type const char *. There is a bit of type coercion going on here. You could just as well declared the function this way: bool openFileIn(fstream&, const char *); .

Also, your openFileIn() function does not return the file name -- it returns a bool.

Regarding your post #21, your new version of openFileIn() is not as good as the previous version, since the filename is hardcoded in the body of the function. The previous version allows the filename to be passed to the function, so the program could conceivably ask the user to enter the filename at run time.

Before moving on, I would advise that you go back and work with pointers some more. There is a fair amount that you don't understand; namely, the type of a string literal (e.g., "demofile.txt"). Several posts in this thread indicate that you don't have a clear understanding in this area.

I modified my code, this time, you can enter the name of the file you choose. Program will ask you to enter the name. I put in "demofile.txt" and it will run EXCEPT it will give me an error I don't understand that it cannot find the .exe file. But when I choose to continue, it runs and give correct answer. I opened the demofile.txt and verify it was written successfully also.
C++:
//12.5 fstream pass by reference to function
#include <iostream>
#include <fstream>
using namespace std;

const int MAX_LINE_SIZE = 81;
bool openFileIn(fstream&, char[]);
void showContents(fstream&);

int main()
{   
    char Ar[81];//
    cout << " Enter the name and extension of file you want to use: ";
    cin >> Ar; cout << "\n\n";//get the name of the file

    ofstream outFile;
    outFile.open(Ar);
    outFile << "This is a test.\n\nAnother test";
    outFile.close();
    fstream dataFile;
    char name[81];
    if (!openFileIn(dataFile, Ar))
    {
        cout << " Fileopen error! \n\n";
        return 0;
    }
    cout << " File opened successfully.\n\n";
    cout << " Now reading data from file.\n\n";
    showContents(dataFile);
    dataFile.close();
    cout << " done.\n\n";
    return 0;
}
bool openFileIn(fstream& file, char Ar[] )
{

    file.open(Ar, ios::in);
    if (file.fail())
        return false;
    else
        return true;
}
void showContents(fstream& file)
{
    char line[MAX_LINE_SIZE];
    while (file >> line)
    {
        cout << line << " ";
    }
    cout << "\n\n";
}

The VS is very strange on my computer, I ran this a few times and it did not show error, all of a sudden it start showing error.
Compile error Listing 7.2.jpg

Let me know is this better. I still don't have to use pointer. Yes, book have not cover pointer to string literal. I can only follow what the book has, I already went beyond the book on pointers. Actually the book doesn't have pointers to pointers. I learned it from you.
Thanks
 
Last edited:
  • #32
yungman said:
The VS is very strange on my computer, I ran this a few times and it did not show error, all of a sudden it start showing error.
The error is a link error, which means that your code compiled without any syntax errors, but for some reason the linker couldn't produce the executable. I would advise this:
1. Under the Build menu, click Clean Solution.
2. Then click Rebuild Solution, also under the Build menu.
See if that works.
yungman said:
Let me know is this better.
It's not better, because it's very confusing, probably because you're working with two different files. Some comments.
1. You have an uninitialized character array, name, that you never use. When you call openFileIn(), you're passing Ar as the name of the file. Did you mean to use the char array (name) instead of Ar?

2. Keep things simple -- just work with one stream, not two (you have outFile and dataFile). Get rid of one of them.

3. It's not clear to me what you're trying to do. After you open a file, you call showContents() for that file, but you've never written anything to it, as far as I can see.

4. Your function name openFileIn() is misleading, as the name implies you are going to be doing input operations on the file; i.e., reading from the file. Since you plan to write some data to the file and then later display the data, this is likely the source of some of your confusion. A file that you are going to write to is an ouput file, so the open mode should be ios:: out, not ios::in. Mode ios::in would be used if you plan to read from the file. See http://www.cplusplus.com/reference/ios/ios_base/openmode/.
You really should change the name of the function. openFileOut() would be a reasonable name.
yungman said:
I still don't have to use pointer.
You don't have to explicitly use pointer notation, but there are pointers being used under the hood. Your character array parameter to your open-file function is char [], which means that what is actually being passed is an address. A pointer is an address.
 
Last edited:
  • Like
Likes sysprog
  • #33
Mark44 said:
The error is a link error, which means that your code compiled without any syntax errors, but for some reason the linker couldn't produce the executable. I would advise this:
1. Under the Build menu, click Clean Solution.
2. Then click Rebuild Solution, also under the Build menu.
See if that works.
It's not better, because it's very confusing, probably because you're working with two different files. Some comments.
1. You have an uninitialized character array, name, that you never use. When you call openFileIn(), you're passing Ar as the name of the file. Did you mean to use the char array (name) instead of Ar?

2. Keep things simple -- just work with one stream, not two (you have outFile and dataFile). Get rid of one of them.

3. It's not clear to me what you're trying to do. After you open a file, you call showContents() for that file, but you've never written anything to it, as far as I can see.

4. Your function name openFileIn() is misleading, as the name implies you are going to be doing input operations on the file; i.e., reading from the file. Since you plan to write some data to the file and then later display the data, this is likely the source of some of your confusion. A file that you are going to write to is an ouput file, so the open mode should be ios:: out, not ios::in. Mode ios::in would be used if you plan to read from the file. See http://www.cplusplus.com/reference/ios/ios_base/openmode/.
You really should change the name of the function. openFileOut() would be a reasonable name.You don't have to explicitly use pointer notation, but there are pointers being used under the hood. Your character array parameter to your open-file function is char [], which means that what is actually being passed is an address. A pointer is an address.
Actually the names are straight out of the book, I just use them. The array name is used in the book, I actually don't use it, must have forgot to delete it. I only use Ar[].

I just do what the original program does in the book. The original program doesn't do any writing nor provide anything about the file to be read. I had to improvise to write something into the file at the beginning of the program in order to read it to proof that I can open and read the demofile.txt in the function. It's not me that design the program, just fix the program from the book to make it work.

Remember I started with the code from the book, I just fix it so it works. I succeeded in passing the object dataFile to and back from the function by reference. That's the main goal of the exercise.

I did the rebuilt, and clean already. Still gave me the problem. My VS is a little funny at times. I have to reload it some time. I am just so busy working on it and hard to stop a few hours to redo the VS.

I am going to look into pointer for string literal, I read on line a little, looks like you can declare char*pt = "This is a test". But I have to read more. My books don't get into pointer that deep, I wonder why. If you have a good link about point to string literal, let me know. I don't think it should be too hard, just have to know the syntax.Below is the program that I design and code all by myself. I pass pointer to point to structure into function with nested structure, function to allocate dynamic memory to store the structure and return back to main. I am responsible for everything in this program. I have no question, it works. The program ask your name, your address, your height and weight and display it back.
C++:
// Dynamic memory pointer to nested structure
#include <iostream>
using namespace std;
const int ad_L = 50, city_L = 20;
const int state_L = 15, zip_L = 11, name_L = 50;

struct Date { int month; int day; int year; };

struct Place
{
    char address[ad_L]; char city[city_L];
    char state[state_L]; char zip[zip_L];
};
struct Measure { int feet; int inches; };

struct Body { Measure height; double weight; };

struct Info//with struct Date and Place as MEMBER variables
{
    char name[name_L]; int empNumber;
    Date birthday;//struct Date birthday
    Place resident;//struct Place resident
    Body measurement;
};
void getMem(Info**);
void getAddress(Info*);
void getBody(Info*);
void getMeasure(Info*);
void getBirthday(Info*);
int main()

{
    Info* sptr;//initialize pointer of structure Info
    getMem(&sptr);//function to allocate memory.
    cout << " Enter your full name: ";
    cin.getline((*sptr).name, name_L);
    getBirthday(sptr);//get birthday
    getAddress(sptr);//get address
    getBody(sptr);//get weight and height

    cout << "\n Name:  " << (*sptr).name <<
        "   Birthday  " << (*sptr).birthday.month << "/" <<
        (*sptr).birthday.day << "/" << (*sptr).birthday.year;
    cout << ".   Address is:  " << (*sptr).resident.address <<
        " " << (*sptr).resident.city << " " << (*sptr).resident.state <<
        " " << (*sptr).resident.zip << "\n\n";
    cout << "   Physical built: " << (*sptr).measurement.height.feet << "ft " <<
        (*sptr).measurement.height.inches << "in and weight: " <<
        (*sptr).measurement.weight << "lbs. \n\n";
    delete sptr;//surrender memory
    sptr = 0;//reset pointer
    return 0;
}
void getMem(Info** sfpt)
{
    Info* Ar = new Info;//allocate dynamic memory for structure Info
    *sfpt = Ar;//assign pointer to return to main.
}

void getBirthday(Info* getB)
{
    cout << " Enter month of your birthday: "; cin >> (*getB).birthday.month;
    cout << " Enter day of your birthday: "; cin >> (*getB).birthday.day;
    cout << " Enter 2 digit of year of your birthday: "; cin >> (*getB).birthday.year;
}
void getAddress(Info* getA)
{
    cin.ignore();
    cout << " Enter your address: "; cin.getline((*getA).resident.address, ad_L);
    cout << " Enter your city: "; cin.getline((*getA).resident.city, city_L);
    cout << " Enter your state: "; cin.getline((*getA).resident.state, state_L);
    cout << " Enter your zip: "; cin.getline((*getA).resident.zip, zip_L);
}
void getBody(Info* getM)
{
    cout << " Enter your height first the feet, then inches.\n\n";

    cout << " Enter feet: "; cin >> (*getM).measurement.height.feet;
    cout << " Enter inches: "; cin >> (*getM).measurement.height.inches;
    cout << endl;
    cout << " Enter your weight: "; cin >> (*getM).measurement.weight;
}
 
Last edited:
  • #34
yungman said:
Below is the program that I design and code all by myself.
Seems to work OK, except that when it asks for the month of your birthday, and you enter the name of the month, the program chokes. It would be helpful to prompt the user to enter the month number 1 ... 12.

One thing that you apparently haven't seen yet is the struct pointer member operator, -> .
Everywhere that you have expressions like this - (*sptr).name, you can replace with this - sptr->name. There are at least a dozen places where you could have done this.
 
  • #35
Mark44 said:
Seems to work OK, except that when it asks for the month of your birthday, and you enter the name of the month, the program chokes. It would be helpful to prompt the user to enter the month number 1 ... 12.

One thing that you apparently haven't seen yet is the struct pointer member operator, -> .
Everywhere that you have expressions like this - (*sptr).name, you can replace with this - sptr->name. There are at least a dozen places where you could have done this.
I like it that way. I know exactly what you mean. I like to keep it obvious.

BTW, I have a LOT of issue with VS. Today, I wasted 2 hours running, it was to the point I deleted the code and still run exactly the same as if the code was there! I rebuilt the solution, I clean solution. I exit out of VS. It was only until I reboot the computer before it willing to actually compile the new modified code!

I have no choice but to delete VS and try to re-install again. Guess what? Even when I choose to un-install the VS, it INSIST in update and it's long. I am still waiting. It even made me take the survey!

I know I might be too ignorant for VS, BUT, VS have ISSUES! I wasted so much time today with VS.
 
Last edited:

Similar threads

  • Programming and Computer Science
2
Replies
65
Views
5K
  • Programming and Computer Science
Replies
33
Views
2K
  • Programming and Computer Science
Replies
22
Views
2K
  • Programming and Computer Science
Replies
8
Views
1K
  • Programming and Computer Science
Replies
12
Views
1K
  • Programming and Computer Science
2
Replies
57
Views
3K
Replies
10
Views
961
  • Programming and Computer Science
Replies
32
Views
2K
  • Programming and Computer Science
3
Replies
75
Views
4K
  • Programming and Computer Science
Replies
4
Views
784
Back
Top