Mysterious Error: Can You See Why?

  • Thread starter Thread starter yungman
  • Start date Start date
  • Tags Tags
    Error
Click For 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.
  • #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:
Technology news on Phys.org
  • #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.
 
  • #51
sysprog said:
@pbuk and @Mark44 I think that your posts are spot-on and very nice work.
I agree, and in the long run, I think that pbuk's comments were more helpful than mine.
 
  • #52
Mark44 said:
I agree, and in the long run, I think that pbuk's comments were more helpful than mine.
That's nice of you ##-## I think that it's a toss-up there. Both of you guys make me wish that I could give more than one 'like' per post.
 
Last edited:
  • #53
Mark44 said:
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.
Thanks for the reply. How do you find the debugger? I ran the program, it just ran, no information. How do you bring up the debugger? You mean in the Debug menu? I never even use that before.

This is the code what the book use, I read the code and I just don't feel it's right, dataFile >> Ar just kept writing to the beginning of the Ar, so it erase the last write. That prompted me to double check what is really inside the Ar after reading the complete file. I don't need the debugger to tell me. What if I need the whole content of the file and work on it?

I guess I mainly want to verify with you guys here. Then I can concentrate on how to read the entire file into the program instead of just printing it out with cout.

Thanks
 
Last edited:
  • #54
pbuk said:
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.
Thanks for the reply.

I actually went through a lot of these. I did not post the stuffs I did at the interim on I actually put a counter how may times the while (!dataFile.eof()) ran.

This is from the book how it read out, I actually question whether it is right, I don't even assume it is right. That's the whole experiment I did yesterday when I ran into problem with VS. Just by analyzing the code, I don't think it really copy the file into the array Ar[].

I don't dare to come right out to say the book is wrong! That's why I phrase it in the question "how come I don't get the content I expect" instead. the book use this same while loop to read in the next few exercise, far as I concern, they NEVER manage to read the complete content of the file into the program. I think I show that already. I just want to confirm this, then I can move on coming up with a way to actually read the whole content of the file.

Thanks
 
  • #55
yungman said:
You mean in the Debug menu? I never even use that before.
Yes, the Debug menu. Yes, I can tell that you haven't used it.
yungman said:
I don't need the debugger to tell me.
Clearly you do need to use it, or you would have been able to understand why your program produced the output that you showed. Output statements can be helpful at times, but they are a very primitive way to debug a program.
yungman said:
I guess I mainly want to verify with you guys here.
I think I can speak for all of us that we would prefer that you make more of an attempt to answer the many questions you raise. The best way to do that is to learn how to use the debug capabilities.
 
  • Like
Likes pbuk, Vanadium 50 and sysprog
  • #56
Mark44 said:
Yes, the Debug menu. Yes, I can tell that you haven't used it.
Clearly you do need to use it, or you would have been able to understand why your program produced the output that you showed. Output statements can be helpful at times, but they are a very primitive way to debug a program.
I think I can speak for all of us that we would prefer that you make more of an attempt to answer the many questions you raise. The best way to do that is to learn how to use the debug capabilities.
So you agree with me that the way of reading into Ar[] according to the book doesn't really copy the content of the file? Just use it to do cout to print it out. That's really what I was trying to ask. If so, I'll find another way to do it.

I am looking into modifying the program using vector and use push_back to copy the complete content of the file into the vector. What is the point of reading the file if one cannot actually copy the file into the program so the program can work on it?

Thanks
 
  • #57
yungman said:
So you agree with me that the way of reading into Ar[] according to the book doesn't really copy the content of the file? Just use it to do cout to print it out. That's really what I was trying to ask. If so, I'll find another way to do it.
The string gets written to the character array with no problem, but using the stream insertion operator, <<, to output it to cout is where the problem lies. The << operator doesn't work well with C-type character arrays. The C standard library functions printf() and scanf() (or scanf_s() when you're using VS) work better with C-type arrays than do the C++ classes, IMO.

yungman said:
I am looking into modifying the program using vector and use push_back to copy the complete content of the file into the vector. What is the point of reading the file if one cannot actually copy the file into the program so the program can work on it?
Using the vector template class isn't scalable. It would be OK for a toy program, but what if the file is 3.0 GB or 5.0 TB? It makes more sense to use a C++ string template class.
C++:
#include <string>
...
string str;
while (!dataFile.eof())
{
    getline(dataFile, str);
    cout << str ;// print out content read from file
}
Here getline() reads characters from the input stream up to the newline character, and writes them to str. The newline character is discarded each time it is encountered.
 
  • Like
Likes jtbell, sysprog and yungman
  • #58
yungman said:
So you agree with me that the way of reading into Ar[]
It would be helpful to you to get the reading and writing terminology straight. You're not "reading into Ar[]" -- you're reading from the input stream (the file), and writing to the array. The words that we use affect how we think about things and how we communicate these ideas to others. Using the wrong words makes it more likely that we write incorrect code.
 
  • Like
Likes Vanadium 50 and sysprog
  • #59
Mark44 said:
The string gets written to the character array with no problem, but using the stream insertion operator, <<, to output it to cout is where the problem lies. The << operator doesn't work well with C-type character arrays. The C standard library functions printf() and scanf() (or scanf_s() when you're using VS) work better with C-type arrays than do the C++ classes, IMO.

Using the vector template class isn't scalable. It would be OK for a toy program, but what if the file is 3.0 GB or 5.0 TB? It makes more sense to use a C++ string template class.
C++:
#include <string>
...
string str;
while (!dataFile.eof())
{
    getline(dataFile, str);
    cout << str ;// print out content read from file
}
Here getline() reads characters from the input stream up to the newline character, and writes them to str. The newline character is discarded each time it is encountered.
I tried your suggestion, it still erase the old data in str every time a new line is read from file and write to str. I don't see this can achieve what I want...to read the stream from file and store the complete content into either an array or vector.

EDIT:
At the mean time, I was looking into using vector push_back and it works to a big extend. I saved all the content AND I can add space artificially. BUT I still yet to make the print out with other delimiters like '\n' for new line. This is what I learn online, this is ONLY the function part, but you should see what I am trying to do:
C++:
void showContents(fstream& file, vector<string>& vec)
{
    char temp[MAX_LINE_SIZE];
    while (!file.eof())
    {
        file >> temp;
        vec.push_back(temp);
        vec.push_back(" ");
    }
    cout << " Read back from file is: \n\n";
    for (int index = 0; index < vec.size(); index++)
        cout << vec[index];
}

I know you said using vector is not the best way, but until I can find another way, this is the only way I can think of with my limited knowledge.

Right now, I can save this in the vector : This is a test. Another test. More test. But I lost the new line. It should be:
This is a test.
Another test.
More test.


If you have a way, please let me know
Thanks
 
Last edited:
  • #60
You lost the newlines because the >> operator considers all "whitespace" to be the same: blank spaces, newlines and tabs. It reads "words" (groups of non-whitespace characters) without regard to the specific kind of whitespace that separates them. It discards the whitespace and gives you only the non-whitespace.

If you want to preserve the line structure of the file, you need to use getline(). It uses newlines as separators. Your code in post #59 is a good starting point for this. Simply use getline() instead of >> to read into temp.

getline() discards the newlines after using them as separators. It doesn't read them into the string. So if you want to display the strings on separate lines as they were in the file, you need to write the newlines yourself, using '\n' or endl.
 
Last edited:
  • Like
Likes sysprog

Similar threads

  • · Replies 65 ·
3
Replies
65
Views
7K
  • · Replies 33 ·
2
Replies
33
Views
3K
  • · Replies 8 ·
Replies
8
Views
2K
  • · Replies 22 ·
Replies
22
Views
3K
  • · Replies 57 ·
2
Replies
57
Views
4K
Replies
12
Views
2K
Replies
10
Views
2K
  • · Replies 32 ·
2
Replies
32
Views
3K
  • · Replies 75 ·
3
Replies
75
Views
6K
  • · Replies 4 ·
Replies
4
Views
1K