2

I have a file contains a list of phone numbers in the following form:

Arvind 72580931
Sachin 7252890

My question is how can we display the contents in two columns?

chema989
  • 3,962
  • 2
  • 20
  • 33
Divya
  • 21
  • 2
  • 3
    http://stackoverflow.com/questions/236129/split-a-string-in-c –  Jun 29 '16 at 05:20
  • 1
    You might find some informative methods from the [io manipulators](http://en.cppreference.com/w/cpp/io/manip) available from the standard library. – WhozCraig Jun 29 '16 at 05:38

2 Answers2

3

First You need to parse each line in the list of phone numbers for get name and phone number. Then You need to format the output, You can use std::setw(int) to specify the width of the output. For example:

#include <iostream>
#include <string>
#include <iomanip>
#include <vector>

std::vector<std::string> stringTokenizer(const std::string& str, const std::string& delimiter) {
    size_t prev = 0, next = 0, len;
    std::vector<std::string> tokens;

    while ((next = str.find(delimiter, prev)) != std::string::npos) {
        len = next - prev;
        if (len > 0) {
            tokens.push_back(str.substr(prev, len));
        }
        prev = next + delimiter.size();
    }

    if (prev < str.size()) {
        tokens.push_back(str.substr(prev));
    }

    return tokens;
}

int main() {
    const int size_name = 20, size_phone = 10;
    std::cout << std::setw(size_name) << "NAME" << std::setw(size_phone) << "PHONE" << std::endl;

    std::vector<std::string> directory = {
        "Arvind 72580931",
        "Sachin 7252890",
        "Josh_Mary_Valencia 7252890"
    };

    for (const std::string& contact : directory) {
        std::vector<std::string> data = stringTokenizer(contact, " ");
        std::cout << std::setw(size_name) << data.at(0) << std::setw(size_phone) << data.at(1) << std::endl;
    }
}

Output:

                NAME     PHONE
              Arvind  72580931
              Sachin   7252890
  Josh_Mary_Valencia   7252890
chema989
  • 3,962
  • 2
  • 20
  • 33
2

If you want to display the output in the form of two columns you can maybe consider adding a tab character (or two) in between them.

cout << "name" << '\t' << "phone" << endl;
Curious
  • 20,870
  • 8
  • 61
  • 146