C++ ファイルを1行ずつ読み取り、区切り文字を使用して各行を分割します 質問する

C++ ファイルを1行ずつ読み取り、区切り文字を使用して各行を分割します 質問する

txt ファイルを 1 行ずつ読み取り、各行を読み取った後にタブ "\t" に従って行を分割し、各部分を構造体の要素に追加したいと思います。

私の構造体は1*charと2*intです

struct myStruct
{
    char chr;
    int v1;
    int v2;
}

chr には複数の文字を含めることができます。

行は次のようになります。

randomstring TAB number TAB number NL

ベストアンサー1

試してください:
注意: chr に 1 文字以上を含めることができる場合は、文字列を使用してそれを表します。

std::ifstream file("plop");
std::string   line;

while(std::getline(file, line))
{
    std::stringstream   linestream(line);
    std::string         data;
    int                 val1;
    int                 val2;

    // If you have truly tab delimited data use getline() with third parameter.
    // If your data is just white space separated data
    // then the operator >> will do (it reads a space separated word into a string).
    std::getline(linestream, data, '\t');  // read up-to the first tab (discard tab).

    // Read the integers using the operator >>
    linestream >> val1 >> val2;
}

おすすめ記事