3

* For those having this problem, it was the problem with my command. Make sure your command to compile and run the program is correct!

I was watching a tutorial on youtube.

I did exactly the same as the op did, and I get a different output.

I am new to c++, and I am using Xcode to run the code.

here is the code: (again, it's not mine, but from a youtube tutorial video)

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    int input[100];
    int x = 0;
    int fail = 0;
    int pass = 0;

    fstream textfile;
    textfile.open("exam.txt");

    while(! textfile.eof()) {
        textfile >> input[x];
        cout << input[x] << endl;
        if(input[x] < 50) {
            fail++;
        }
        else {
            pass++;
        }
        x++;
    }
    textfile.close();
    cout << fail << "students out of " << (fail + pass) << "did not pass the exam." << endl;

    return 0;}

It's supposed to print grades.

But this is what I get when I run it on Xcode.

0
0
0
0
0
0
0
0
1606415288
32767
1606415720
32767
1606415720
32767
2003953588
1294056514
104
1
1606415312
32767
25240
1
1606415288
32767
1606415312
32767
25248
1
1606415288
32767
1606415312
32767
1606415720
32767
25264
1
1606415304
32767
1606415720
32767
1606415720
32767
6144
1
1910210376
32767
1606416728
32767
0
0
0
0
0
0
0
0
0
0
1606416544
32767
2003953588
1294056514
1606416544
32767
-1988827167
32767
0
0
1
0
1606416904
32767
0
0

It's only part of the output. It doesn't terminate.

Also, when I try to run it on linux (sshed into school linux machine),

I get this following error:

    @@?!@8  @ @@@@@?88@8@@@?? ??`?`?? ``?TT@T@DDP?tdPP@P@DDQ?tR?td??`?`  /lib64/ld-linux-x86-64.so.2GNUGNU?Yd?`˫sP???*??"b!!??  (E?L?
                                             CyIk?  ^Q#y??K@??'?[?
@3P
@ `??
@libstdc++.so.6__gmon_start___Jv_RegisterClasses_ZNSt8ios_base4InitD1Ev_ZNSt13basic_fstreamIcSt11char_traitsIcEEC1Ev_ZNSt13basic_fstreamIcSt11char_traitsIcEE5closeEv_ZNSirsERi_ZNSt13basic_fstreamIcSt11char_traitsIcEE4openEPKcSt13_Ios_Openmode__gxx_personality_v0_ZSt4cout_ZNSolsEi_ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_PKc_ZSt4endlIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6__ZNSt13basic_fstreamIcSt11char_traitsIcEED1Ev_ZNSolsEPFRSoS_E_ZNKSt9basic_iosIcSt11char_traitsIcEE3eofEv_ZNSt8ios_base4InitC1Evlibgcc_s.so.1_Unwind_Resumelibc.so.6__stack_chk_fail__cxa_atexit__libc_start_mainGCC_3.0GLIBC_2.4GLIBC_2.2.5CXXABI_1.3GLIBCXX_3.4 P&y
xui     ?ӯk?t)??`? `  ` ` `  `( `0 8 `  @ `                            p60ii
H `
   P `
` `h `p `x `? `H??c????H???5? ?%? @?%? h??????%? h??????%? h??????%? h?????%? h?????%? h?????%? h?????%? h?p????%? ?`????%? h   ?P????%? h
?@????%? h
          ?0????%? h
?????%z h?????%r h??????%j h?????1?I??^H??H???PTI???@H??0@H??
                                                             @????????H?H?? H??t??H?Ð????????????UH??SH??=0 uK?`H?* H???`H??H??H9?s$fDH??H? ???`H?? H9?r??? H?[]?fff.?H?=  UH??t?H??]`??]Ð?UH??SH???dH?%(H?E?1?Dž????Dž????Dž????H??????H???T???????H???????@H???????|H??0?????????Hc?H??H?H??????H??H???$?????????H????0????ƿ? `?Y?????
@H???
     ?????????H????0?????1  ???????????????????H??????H???????????d???H??????H???R???????????????????????ƿ? `??????%@H????????H???????6@H?????????
@H???`????H??????H?????????H?U?dH3%(t$?H??H??????H???????H??H???L????????H???[]?UH??H???}??u??}?u*?}???u!??!`?6????P
@?? `??!`H?????????UH?????????]?UH??}??u??U??E? ?]Ð???H?l$?L?d$?H?-? L?%? L?l$?L?t$?L?|$?H?\$?H??8L)?A??I??H??I???k???H??t1?@L??L??D??A??H??H9?u?H?\H?l$L?d$L?l$ L?t$(L?|$0H??8???Ð?????????????UH??SH?H H???t??`DH???H?H???u?H?[]Ð?H??_???H??exam.txtstudents out of did not pass the exam.D????`?????s?????????????????0p???XzRx
                              $H??? FJ
O                                     ??;*3$"D8???A?C

I used this command: g++ main.cpp -o output.out Is there something wrong with my command?

Thank you so much!!!

Nayana
  • 1,321
  • 3
  • 18
  • 32
  • 10
    Please do not watch C++ tutorials on YouTube. –  Jun 20 '13 at 21:50
  • 1
    The errors you're reporting on Linux do not match the source code you're trying to compile. I think you may be compiling the wrong file. – templatetypedef Jun 20 '13 at 21:51
  • Maybe you should consider to change the tutorial or learn C++ differently. – Ralph Tandetzky Jun 20 '13 at 21:53
  • 3
    @TonyTheLion Surely, you were once this naive at the beginning? Why the hate? – dchhetri Jun 20 '13 at 21:53
  • @user814628, meet Tony. Tony's a troll when bored / drunk. Flag and move on. – millimoose Jun 20 '13 at 21:55
  • Line 20 summarizes your question nicely :) – fredoverflow Jun 20 '13 at 21:56
  • why's this question being downvoted? – Chaos Jun 20 '13 at 21:59
  • 3
    It's a bad habbit using `textfile.eof()` as it checks for the eof flag which appears only when you try to read above the end of file. It doesn't predict the aperence of EOF. Better write `while(textfile >> input[x]){}` – Alexandru Barbarosie Jun 20 '13 at 22:07
  • Sorry, everyone. I ran a wrong file on linux, linux give some weird output I can't even read. I updated my question. Thank you. – Nayana Jun 20 '13 at 22:17
  • @Alexandru: it's actually bad of `eof()` to return true not when we are in fact at the end of file, but when the class actually has noticed it. – Vlad Jun 20 '13 at 22:24
  • Here's a very nice tutorial: http://www.cplusplus.com/doc/tutorial/ :) (not an answer to the question, but a good resource if you're looking for one) – Nathan Jun 20 '13 at 22:29
  • @Vlad: It's not "bad"; it makes perfect sense. – Lightness Races in Orbit Jun 20 '13 at 22:29
  • @Lightness: were it so, the other languages would have the same quirk. However they do not. – Vlad Jun 20 '13 at 22:30
  • @Nayana I also ran your code in my VS 2010 and it worked properly. – Alexandru Barbarosie Jun 20 '13 at 22:31
  • @Vlad that's what I was trying to say. – Alexandru Barbarosie Jun 20 '13 at 22:32
  • @Alexandru: really? Maybe I do not have proper environment set up for C++. Can you think of what I am missing? But when I run it on school linuc machine, it still doesn't run though... I am even more lost now.. – Nayana Jun 20 '13 at 22:34
  • @Alexandru: I see now, didn't understand your remark. – Vlad Jun 20 '13 at 22:35
  • @Nayana unfortenytly I can not say anything the environment. The thing you should defenetly do is change your `while`loop condition as I specified above. Also try `ifstream` instead of `fstream` – Alexandru Barbarosie Jun 20 '13 at 22:38
  • @Nathan: Those tutorials are not "very nice"; they are in fact mostly full of rubbish. Please do not link to them. – Lightness Races in Orbit Jun 20 '13 at 22:48
  • @Vlad: Your argument lacks substance. Does C++'s `constexpr` keyword make no sense just because no other language has one? – Lightness Races in Orbit Jun 20 '13 at 22:48
  • 1
    @Lightness: nevertheless, most languages have `eof()` with semantics "end of file, really" and not "I have detected end of file and stored a flag about it". That is a different story, right? – Vlad Jun 20 '13 at 22:59
  • @Vlad: I don't think it's unreasonable for `eof` to mean "you reached the end of the file, as detected the last time you polled the file for something", rather than "I think that you're about to hit the end of the file". – Lightness Races in Orbit Jun 21 '13 at 00:08
  • @Lightness: The other languages out there define `eof()` as 'you are at the end of file, period'. This means that it must be possible to define such a function in C++, too. Function having the semantic 'you are either indeed at the end of file or I didn't detect yet so I say _no_' (despite having perfectly defined meaning) must not be called `eof()`. It would be hypocritical to blame the novice language users because they didn't look up the documentation. – Vlad Jun 21 '13 at 11:19
  • @Lightness: Frequent newcomers' mistakes in using of `eof()` only confirm what I say. If the meaning of function name contradicts the documentation, something is wrong. – Vlad Jun 21 '13 at 11:23
  • @Vlad: The meaning of the function name does not contradict the documentation. `eof()` is true when the EOF flag has been set on the stream. – Lightness Races in Orbit Jun 21 '13 at 13:08
  • @Vlad: Newcomers frequently get pointers wrong, too. Is that because pointers work differently in other languages? Partially. It's more because newcomers are newcomers. Does it make C++ pointers _wrong_? No. / In *this* case, people get `.eof` wrong because they follow crappy, lying tutorials on cplusplus.com, not because C++ is wrong. – Lightness Races in Orbit Jun 21 '13 at 13:30
  • @Lightness: about the EOF flag: either the flag is purely internal thing (so the actual binding of the function to the flag is irrelevant for the proper naming), or the flag is a part of a standard interface (so its name itself is totally misleading). Let me reiterate my point: although the function having the discussed semantic has a right to exist, its name is totally terrible because it _contradicts_ the actual semantic. – Vlad Jun 25 '13 at 21:36
  • @Lightness: The fact that people often get the pointers wrong is slightly offtopic: we are discussing the _naming_ here. Let's first establish that consistent naming is important: defining a library function named `cos` and returning sine value, albeit being completely ok from theoretical point of view (α-conversion bla bla bla) is dishonest w.r.t. the users: they need to learn a totally unnecessary quirk, specific to the given library only, and this quirk carries no value for them. The frequent beginners' mistakes in this case are just a justification of a bad naming scheme. – Vlad Jun 25 '13 at 21:44
  • @Lightness: My note about other languages implementing `eof` in a semantically correct way was to preemptively address the possible attack on my argument: one might say that the only reasonable way to implement `eof` would be only the way it's done in C++. But since the other languages are able to implement the function with "real true genuine honest end of file"-semantic, C++ being not worse than others must be able, too. – Vlad Jun 25 '13 at 21:55

2 Answers2

3

You're doing some dodgey things. As mentioned already, don't test eof. You actually need to test whether your input was successful and/or whether the stream is good. You can have a catch-all when you're reading streams:

while( infile )
{
    //...
}

I mentioned also that you need to check that the value was read. It could be that an integer cannot be read because the input stream does not contain something that looks like an integer, or perhaps some other error occurred. Since you're only reading one integer at a time, you can test that operation by itself. If the stream was bad to begin with (eg the file could not be opened) it will fail straight away:

while( infile >> input[x] )
{
    //...
}

I wouldn't generally use the above approach if reading more than one value each time, because the loop condition gets cluttered. Here's an alternative:

while( infile )
{
    if( !(infile >> input[x]) ) {
        cout << "Failed to read value " << x+1 << endl;
        break;
    }

    //...
}

Let's roll with that, because it's more useful when you wanna find out what's going on. The next thing is that you have a fixed-size array with 100 values. If you read too many values, you are going to overflow. So you need to make sure this won't happen:

while( infile && x < 100 )
{
    if( !(infile >> input[x]) ) {
        cout << "Failed to read value " << x+1 << endl;
        break;
    }

    cout << input[x] << endl;

    if( input[x] < 50 )  {
        fail++;
    } else {
        pass++;
    }

    x++;
}

Now, it seems to me that you're not even using the array, so why keep it at all? You could just read into a temporary value:

    int grade;
    if( !(infile >> grade) ) break;
    // ...

But if you wanted to keep the array and didn't know how many grades you might end up reading, use a vector<int> instead of an int array. I'll show this with the simpler loop style:

std::vector<int> grades;
int grade;

while( infile >> grade )
{
    grades.push_back(grade);
    //...
}

Notice how I've used more descriptive variable names. Something like input doesn't tell you much about what it contains. That is the kind of variable name you'd get from an inexperienced programmer whose YouTube videos you should immediately boycott.

The last thing I'll suggest is using ifstream instead of fstream, because by default you don't need to open the file in read/write mode. You could supply flags to fstream::open, but why do that when you can just construct ifstream like this:

ifstream infile("exam.txt");

You also don't need to explicitly close it, because that will happen when infile's destructor is called.

paddy
  • 52,396
  • 6
  • 51
  • 93
  • Thank you so much for detailed explanation. I should not watch Youtube tutorials. I know Java, so I thought I could just watch some short tutorials and pick up the language. – Nayana Jun 20 '13 at 22:55
  • BTW, it turns out that my program does not even get the input successfully. It never goes into the while loop. It now only print "0students out of 0did not pass the exam." – Nayana Jun 20 '13 at 22:56
  • paddy, maybe you should read the answers [here](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) as well... – Mooing Duck Jun 20 '13 at 22:57
  • @MooingDuck I don't get your point. I am familiar with the content in those answers. Assuming I received a negative vote from you for something I've written, and I can only assume it's about the fact that I terminate on both stream error *and* invalid input. That is by design. It's up to the author to handle bad input if they want. If I've missed your point, please elaborate. – paddy Jun 20 '13 at 23:10
  • 1
    @Nayana That generally indicates that your file could not be opened. Most likely the current directory is not where you think it is. – paddy Jun 20 '13 at 23:10
  • It just a .txt file with integers typed in each row. I can't seem to figure out why it can't be opened. – Nayana Jun 20 '13 at 23:12
  • All of your code samples show what I would consider to be bad (though working) code. Usually I see a `if (infile)` to check if the file opened at all, and then `while(infile >> data)` to read it. Your code is far more complicated. – Mooing Duck Jun 20 '13 at 23:12
  • @Nayana: if a file can't be opened, that has nothing to do with the contents, and almost everything to do with where the text file is on your hard drive. Either move it to the "current" folder, or use the complete file path starting with a drive letter. – Mooing Duck Jun 20 '13 at 23:14
  • Sometimes your pedantic nature is cool and helpful, while other times it's a bit petty. If I were to take all the `good` out of this code, would you admit that it's not bad? – paddy Jun 20 '13 at 23:24
  • My program file and the text file are all in the same directory... – Nayana Jun 20 '13 at 23:28
  • @nayana are you *running* your program from that directory too? Another common issue is that the file is locked by some other process (such as a text editor), so check that too. If in doubt, use the full path in the filename and see if that works - if so, then your current directory is not where you think it is (if using windows, make sure to escape each backslash with an additional backslash. – paddy Jun 20 '13 at 23:35
  • Someone said it ran fine on their machine, I simply can't understand it doesn't on mine. I am running in Xcode so my current directory doesn't matter. It's all in the same folder. When I run it on linux machine, I get different output but that output looks so bizarre, like it looks in my question above. – Nayana Jun 20 '13 at 23:54
  • 1
    Show me the exact command-line you use to build the program in Linux, and then show the exact command-line you use to run the program. – paddy Jun 20 '13 at 23:58
  • It was the problem with my command, thank you, paddy! – Nayana Jun 21 '13 at 02:12
-3
    #include <iostream>
#include <fstream>
#include <string>
using namespace std;

void main ()
{
        string STRING;
    ifstream infile;
    infile.open ("names.txt");
        while(!infile.eof) // To get you all the lines.
        {
            getline(infile,STRING); // Saves the line in STRING.
            cout<<STRING; // Prints our STRING.
        }
    infile.close();
    system ("pause");
}

I hope, this code can help you.

oguzhancerit
  • 1,251
  • 1
  • 11
  • 22
  • 1
    how would this code help? – moooeeeep Jun 20 '13 at 21:55
  • Thank you so much for your comment, your code make sense to me. But my input file has integers in it, so when I replace string with int, the line, "getline(ingile, STRING)" causes an error, saying "No matching function for call to 'getline'." – Nayana Jun 20 '13 at 22:24
  • I replaced the line, "getline(ingile, STRING)", with "infile >> STRING." It compiles now, but the output looks weird. It only print 0 infinitely. – Nayana Jun 20 '13 at 22:30
  • 1
    -1: This code is simply awful. Sorry. – Lightness Races in Orbit Jun 20 '13 at 22:48