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?
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?
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
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;