Srijit B
Srijit B

Reputation: 59

Reading from files in C++

A file contains a list of telephone numbers in the following form :

John            23456
Ahmed        9876
Joe 4568

The names contain only word and the names and telephone numbers are separated by white spaces. Write a program to read the file and output the list in two columns. The names should be left-justified and the numbers right-justified.

I was able to remove whitespace and display it but cannot align it in output.

#include<iostream>
#include<fstream>
#include<conio.h>
using namespace std;
main()
{
    fstream file,f2;
    file.open("list.txt",ios::in|ios::out);
    f2.open("abcd.txt",ios::out);
    file.seekg(0);

    char ch,ch1;
    file.get(ch);

    while(file)
    {
        ch1 = ch;
        file.get(ch);

        if( ch == ' ' && ch1 != ' ')
        {
            f2.put(ch1);
            f2.put(' ');
        }

        if(ch != ' ' && ch1 != ' ')
            f2.put(ch1);
    }

    file.close();
    f2.close();
    getch();
}

Upvotes: 0

Views: 2058

Answers (2)

sehe
sehe

Reputation: 392833

Simplest straightforward (no paranoid input format checking):

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

int main()
{
    std::ifstream ifs("list.txt");

    std::string name; int val;
    while (ifs >> name >> val)
    {
        std::cout << std::left  << std::setw(30) << name << 
                     std::right << std::setw(12) << val << std::endl;
    }
}

Output:

John                                 23456
Ahmed                                 9876
Joe                                   4568

Upvotes: 2

EddieBytes
EddieBytes

Reputation: 1343

You can simply set the appropriate flags on your output stream (f2 is the output stream in your case). See the following article: http://www.cplusplus.com/reference/ios/ios_base/width/

For your example, replace cout with f2 since they're both output streams inheriting from ios_base.

Upvotes: 0

Related Questions