8

以下の形式のファイルがあります

mon 01/01/1000(TAB)こんにちはこんにちは(TAB)お元気ですか

'\t'区切り文字として (スペースではなく) 単独で使用するような方法でテキストを読む方法はありますか?

したがって、サンプル出力は次のようになります。

月 01/01/1000

こんにちはこんにちは

げんき

fscanf()最初のスペースまでしか読み取れないため、使用できませんでした。

4

2 に答える 2

12

標準ライブラリ機能のみを使用:

#include <sstream>
#include <fstream>
#include <string>
#include <vector>

std::ifstream file("file.txt");

std::string line;

std::vector<std::string> tokens;

while(std::getline(file, line)) {     // '\n' is the default delimiter

    std::istringstream iss(line);
    std::string token;
    while(std::getline(iss, token, '\t'))   // but we can specify a different one
        tokens.push_back(token);
}

ここでさらにアイデアを得ることができます: How do I tokenize a string in C++?

于 2012-05-16T12:04:51.163 に答える
5

ブーストから:

#include <boost/algorithm/string.hpp>
std::vector<std::string> strs;
boost::split(strs, "string to split", boost::is_any_of("\t"));

そこに任意の区切り文字を指定できます。

于 2012-05-16T11:01:07.737 に答える