Mysterious Error: Can You See Why?

  • Thread starter Thread starter yungman
  • Start date Start date
  • Tags Tags
    Error
AI Thread Summary
The discussion revolves around a mysterious error encountered in a C++ program where two identical code blocks are used, but only one compiles successfully. The user initially copied the content from a working `main()` function to a non-working one, yet the latter produced a compile error due to a missing `int` before `main()`. Participants emphasized the importance of checking compiler error messages, as they can guide users to the source of the issue, which in this case was the incorrect function signature. Additionally, it was clarified that compile errors prevent the creation of an executable file, while link errors occur after an object file is generated. The conversation highlights the need for careful attention to detail in coding and understanding compiler feedback.
yungman
Messages
5,741
Reaction score
294
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
They are not exactly the same... :wink:
 
  • Like
Likes sysprog
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.
 
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
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
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
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?
 
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.
 
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:
  • #36
I might be new with VS. But I spent decades using different pcb layout software, Microwave Office for RF simulation, LTSpice, Schematic capture and other simulation programs. VS HAS PROBLEMS! It is NOT user friendly to put it in the MOST polite way. I never seen any simulation program that will give simulation result of the old program no matter how you change the program, clean, reset, even get out of the program and re-enter the program. Have to restart the computer to resolve the problem. You don't even know when to trust the result.

BELIEVE me, there are PLENTY of free programs like LTSPICE, pcb layout programs. NONE have problem even close to like VS.

I wonder there is any other C++ compiler I can use. I TOTALLY LOST FAITH in VS at this point.
 
  • #37
What I said a few weeks ago was that I thought your installation of VS isn't right. I've been using VS in at least 5 different editions for 22 years on maybe 10 different computers. I've never had any of the issues you mention.

Surely you can uninstall VS completely, and then install it fresh. You might have to pay attention along the way to keep it from doing an update instead of uninstalling.

I suspect that all of the programs you mentions, like LTSPIC and others, are much smaller and deal with a much smaller language. If you decide to get away from VS, you could install the GNU compiler, called gcc. I've never used it, but on the one hand it's free, but my sense is that it is not as user-friendly.
 
  • Like
Likes sysprog
  • #38
Again, I think that version control may be a concern ##-## as I said in post #13:
sysprog said:
I think that sufficiency of version control may be at issue.
I think that blaming the VS IDE instead of looking at possible faults in your own rapid acquisition of new-to-you knowledge may be a mistake ##-## please look again at your implementations ##\dots##
Quote
 
  • #39
sysprog said:
Again, I think that version control may be a concern ##-## as I said in post #13:

I think that blaming the VS IDE instead of looking at possible faults in your own rapid acquisition of new-to-you knowledge may be a mistake ##-## please look again at your implementations ##\dots##
Quote
No, I am talking about writing to file, reading back from file AFTER I delete all the code and leaving only 4 lines in the program like int x; cin >> x; cout x! None of of fstream code are there and still it write to file. I verify that by deleting the content of the file and it was re-written into the file again...without the code! I exit the program, closed the program and re-opened it and did the same thing! It's like magic code that do things without code!

Anyway, I uninstalled the VS, then download and reinstalled again, we'll see what happen. Whole day wasted again.
 
  • #40
So far the new VS gives me no problem. I am moving on back to my original program:
C++:
//Write Murphy address
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
    fstream dataFile;
    dataFile.open("C:\\Users\\alanr\\Desktop\\C++ exercise\\Gaddis\\inout files\\demofile.txt", ios::out);
    dataFile << " Jane Murphy \n 47 Jones Circle\n Almond, NC 28702 \n\n";
    dataFile.close();

    const int L = 81; //length of Ar[]
    char Ar[L];
    int index = 0;
    dataFile.open("C:\\Users\\alanr\\Desktop\\C++ exercise\\Gaddis\\inout files\\demofile.txt", ios::in);
    while (!dataFile.eof())
    {
        dataFile >> Ar;
        cout << Ar << " ";// print out content read from file
    }
    cout << "\n\n after reading \n\n";
    cout << Ar << "\n\n";//try to print out again.
  
    for (index = 0; index < 30; index++)
        cout << Ar[index];
    return 0;
}
// from line 20:   Jane Murphy 47 Jones Circle Almond, NC 28702

//line 22:   after reading
// nothing from line 23.// from line 26:   8702, ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠

I put the result in the comment at the bottom of the code. As you can see, in line 20, the content of Ar print out just fine. BUT I want to print out Ar again in line 23, I got nothing. I don't understand why. I should get the same output as from line 20.

I tried using for loop in line 26 to print out Ar, you can see the garbage. What did I do wrong? The for loop will just print out 30 characters, you can see only the last 4 characters 8702 are in Ar.

My whole experiment is to check what's in the book when their program claimed they read on from file and stored in an array. I cannot proof that here.

Thanks
 
  • #41
yungman said:
No, I am talking about writing to file, reading back from file AFTER I delete all the code and leaving only 4 lines in the program like int x; cin >> x; cout x! None of of fstream code are there and still it write to file.
It seems obvious to me that after you deleted all but four lines of code, you didn't rebuild the program. What you're running is from a previous build.
yungman said:
It's like magic code that do things without code!
No, there's no magic here.
 
  • Like
Likes sysprog and Vanadium 50
  • #42
yungman said:
Anyway, I uninstalled the VS, then download and reinstalled again, we'll see what happen. Whole day wasted again.
I think that it's not a waste of your time for you to deal with your problems. I remind you that you're trying to learn things that are new to you. If @Mark44 gives you guidance then he's doing you (and anyone else reading) a favor; you don't to me seem to be ungrateful; however, your rancor regarding a "whole day wasted again" seems to me to be rather impatient ##-## as you know, learning something may take time.
 
  • Like
Likes Vanadium 50 and Mark44
  • #43
I think that it's not unreasonable to find annoying the quirks of whichever IDE you're using, but I also think that it's likely that it would be better to be patient and continue to learn, than it would be to hurry off to a possibly not as good environment. I sometimes use VS to interface to MASM, but I mostly don't use its editor ##-## I mostly use notepad++ for Intel or Motorola or nix or net code ##-## when I'm writing IBM mainframe assembly language code, I most of the time use a version of ISPF/PDF ##-## I think that VS is good once you understand it and cope with its ideosyncrasies ##-## and for C++ I think of the MS compiler as canonical.
 
Last edited:
  • #44
Mark44 said:
It seems obvious to me that after you deleted all but four lines of code, you didn't rebuild the program. What you're running is from a previous build.
No, there's no magic here.
I first want to make sure you know that I appreciate your help and other people's help.

After you told me a while back to rebuilt solution, that's the first thing I do every time. I also do clean solution. They did not help this time. I did these two steps over and over already. Like I said, I even exit VS, close down VS and re-open VS, still behaved the same. It was not until I restart the computer that it got out of that mode. I followed your advice by heart.

I reinstalled VS, we'll see how it works this time.

Thanks
 
  • #45
sysprog said:
I think that it's not a waste of your time for you to deal with your problems. I remind you that you're trying to learn things that are new to you. If @Mark44 gives you guidance then he's doing you (and anyone else reading) a favor; you don't to me seem to be ungrateful; however, your rancor regarding a "whole day wasted again" seems to me to be rather impatient ##-## as you know, learning something may take time.
I appreciate all the help from you and Mark. Yes, I am getting impatient as I feel I could have learn faster in my younger days. It's been exactly two months I started already, just finished the normal C++ class. That's slow in my book. The next few lessons is getting harder and harder and it's frustrating the VS is stopping me. Took me a while to realize that, it wasn't obvious at first, I thought I did something wrong with my code. Took a while until I deleted all the relevant lines and just put in some cin and cout to confirm it's VS's problem.

I used to study a lot faster, still have a lot of drive to learn more, just the mind is just not as fast as before and tends to forget things, that's the most frustrating thing.

Thanks
 
  • #46
BTW, can you take a look at post #40 above. That's the program that started the whole VS problem. I question the code from line 17 to 21 whether it actually read in the file and store into the char Ar[]. I cannot read it back as shown.

Thanks
 
Last edited:
  • #47
yungman said:
I used to study a lot faster, still have a lot of drive to learn more, just the mind is just not as fast as before and tends to forget things, that's the most frustrating thing.
I can relate ##-## I think that I'm not as quick on the uptake as I once was ##-## I'm grateful that I can still learn things ##\dots##
 
  • Like
Likes yungman
  • #48
yungman said:
BTW, can you take a look at post #40 above. That's the program that started the whole VS problem. I question the code from line 17 to 21 whether it actually read in the file and store into the char Ar[]. I cannot read it back as shown.

Thanks
I don't think it will do you any good if you were told why the code does not do what you expect it to. You should work it out for yourself:
  • Work through each line of the code on paper, working out the contents of each variable after each operation.
  • Insert some debugging code to check that what is happening is what you really think is happening. Bear in mind that a char type can contain values from 0-255; not all of these values translate to characters that will display on the screen so it is pointless using cout on a character array/C-string type, how can you display the ASCII code of each 'character' instead? (hint: the code stored in Ar[0] at the end of the program is a big clue to what is going on).
  • Think carefully about your control structures: how many times does your while (!dataFile.eof()) loop execute? Check your answer with some debugging code. This should give you some insight into what values Ar is taking as your code executes; again, check this with debugging code.
In summary it is not possible to debug programs by staring at the code saying 'this must be right' or by looking things up on the internet. You debug code by printing out values of variables at key points (or when you are desparate, after every statement) until you understand why it is not doing what you want it to.
 
  • Like
Likes Mark44 and sysprog
  • #49
yungman said:
BTW, can you take a look at post #40 above. That's the program that started the whole VS problem. I question the code from line 17 to 21 whether it actually read in the file and store into the char Ar[]. I cannot read it back as shown.
Here's the code in question:
C++:
while (!dataFile.eof())
{
    dataFile >> Ar;
    cout << Ar << " ";// print out content read from file
}
cout << "\n\n after reading \n\n";
cout << Ar << "\n\n";//try to print out again.

The while loop reads one "word" at a time from the input file, with Ar being successively set to Jane, Murphy, and so on. The next to last read puts the string 28702 into Ar. The last read puts the null character into Ar, which now has \0, '8', '7', '0', '2', and the loop exits.

The first output statement prints the prompt. The second prints the string whose 0-index character is the null character, so nothing appears.

When you loop through Ar in the final loop, you get \0, '8', '7', '0', '2' and whatever garbage happens to be left over in the array.

You should work on getting more familiar with the debugger -- it can show you step by step what is happening.
 
  • Like
Likes sysprog
  • #50
@pbuk and @Mark44 I think that your posts are spot-on and very nice work.
 

Similar threads

Back
Top