1

I have the txt file which contains for example:

Arthur 20

Mark 21

Josh 12

The are no empty lanes between, its only for readability!

What I want to do is write it on the screen in the same way as it is in the file.

I tried to make it this way:

ifstream file;
string word;

file.open("data.txt");
while(!file.eof()){

    file >> word;

    if(file.fail())
    break;

    cout << word << " ";
    file >> word;
    cout << word << endl;
}

But the output is:

Arthur 20

Mark 21

Josh 12

0

So why this 0 is being caught as a empty line to my string variable? I thought that fail() should stop the loop and leave me with correct output?

Slajni
  • 105
  • 1
  • 10

1 Answers1

0

as long as you have names which don't contain white spaces and age as integer then you can read name as a string and age as an integer.

you don't need to check whether the file was successfully opened or not you can just abbreviate the operation:

#include <iostream>
#include <fstream>
#include <string>


int main()
{

    std::ifstream file;
    std::string   word;
    int age;

    file.open("data.txt");

    while( file >> word)
    {
        file >> age;
        std::cout << word << "   " << age << std::endl;
    }


    std::cout << std::endl;
    return 0;
}
  • if you want to use one variable and for sure a string one then:

    while( file >> word)
    {
        std::cout << word << "   ";
        file >> word;
        std::cout << word << std::endl;
    }
    

I don't see any good thing to read age as a string and maybe later convert it back to an integer!

the output:

Arthur   20
Mark   21
Josh   12
Raindrop7
  • 3,889
  • 3
  • 16
  • 27