0

So, I have the text file that looks like this:

3434343434343 3434343434343 sam THOMAS

and I want to save each item into seperate variables. till now I have done:

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;

int main() {
string nd, st;
long long C,N;
ifstream myfile("input.txt");
if (myfile.is_open())
{
    while (!myfile.eof())
    {
        myfile >> C;
        myfile >> N;
        myfile >> nd;
        myfile >> st;
        cout << C << N << nd << st <<endl;


    }

    myfile.close();

}

else cout << "Unable to open file";

return 0;
}

I get 3434343434343 3434343434343 sam THOMAS 3434343434343 3434343434343 sam THOMAS Press any key to continue . . . Why do I get 1 extra lines?

  • 4
    Were you going to ask a question ? And fyi, neither of those numbers will fit in an `int` unless your platform has 64bit native integer types. – WhozCraig Feb 10 '18 at 20:34
  • 2
    Besides the complete lack of a question, the shown code [is completely wrong, anyway](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong). – Sam Varshavchik Feb 10 '18 at 20:35
  • Now you *do* save input from the file in separate variables. Perhaps what you're really looking for is *structures* or *classes*? And perhaps [a couple of good books](https://stackoverflow.com/a/388282/440558)? – Some programmer dude Feb 10 '18 at 20:36
  • Pop quiz, what do you get from `int i=3434343434343;`. Try running, and see what you get. What do you get in `i`? No, it's not "3434343434343". Once you figure why you get what you get, you'll figure out the answer to your own question. Good luck! – Sam Varshavchik Feb 10 '18 at 20:38
  • The numbers in your text file do not fit in an `int`. On most platforms, `int` is only 32-bit (-2147483648 to 2147483647). Try to use `long long C, N;`. – zett42 Feb 10 '18 at 20:40
  • Now that you changed `int` to `long long`, you get an "extra line" because of the link Sam provided in the second comment to this question. Follow it, and see what you did wrong. Related, woe be unto those that fail to check success and/or failure results of their I/O operations. Other than the open-check, there isn't a single check for I/O success in this code. Instead, you're assuming they all just "work"; *don't do that*. – WhozCraig Feb 10 '18 at 20:55

0 Answers0