【问题标题】:How to separate a word with white spaces into two columns in C++如何在C ++中将带有空格的单词分成两列
【发布时间】:2016-10-31 15:31:46
【问题描述】:

我有一个文件包含以下格式的电话号码列表:

Arvind 72580931
Sachin 7252890

我的问题是如何将内容显示在两列中?

【问题讨论】:

标签: c++ output-formatting


【解决方案1】:

首先,您需要解析电话号码列表中的每一行以获取姓名和电话号码。然后你需要格式化输出,你可以使用std::setw(int)来指定输出的宽度。例如:

#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;
    }
}

输出:

                NAME     PHONE
              Arvind  72580931
              Sachin   7252890
  Josh_Mary_Valencia   7252890

【讨论】:

    【解决方案2】:

    如果您想以两列的形式显示输出,您可以考虑在它们之间添加一个(或两个)制表符。

    cout << "name" << '\t' << "phone" << endl;
    

    【讨论】:

      猜你喜欢
      • 2011-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-11
      • 2012-05-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多