簡體   English   中英

strtok或std :: istringstream

[英]strtok or std::istringstream

我有以下代碼,該代碼使用strtok從txt文件接收輸入。 txt文件中的輸入為:

age, (4, years, 5, months)
age, (8, years, 7, months)
age, (4, years, 5, months)

我的代碼如下:

char * point;
ifstream file;
file.open(file.c_str());

if(file.is_open())
{
    while(file.good())
    {
        getline(file, take);
        point = strtok(&take[0], ", ()");
    }
}

除缺少第二年齡和第三年齡的輸出外,它運行良好。 誰能告訴我他們為什么失蹤?

我也嘗試過istringstream但是每當我輸入文件名時,程序就會崩潰。

char * point;
char take[256];
ifstream file;
file.open(file.c_str());

if(file.is_open())
{
    while(file.good())
    {
        cin.getline(take, 256);
        point =strtok(take,", ()");
    }
}

就個人而言,我會使用std::istringstream但會以不同的方式使用它(...,是的,我知道我也可以使用sscanf() ,並且代碼會更短,但我不喜歡類型不安全的接口)! 我會和機械手玩把戲:

#include <iostream>
#include <sstream>
#include <string>

template <char C>
std::istream& skip(std::istream& in)
{
    if ((in >> std::ws).peek() != std::char_traits<char>::to_int_type(C)) {
        in.setstate(std::ios_base::failbit);
    }
    return in.ignore();
}

std::istream& (*const comma)(std::istream&) = &skip<','>;
std::istream& (*const open)(std::istream&) = &skip<'('>;
std::istream& (*const close)(std::istream&) = &skip<')'>;

struct token
{
    token(std::string const& value): value_(value) {}
    std::string::const_iterator begin() const { return this->value_.begin(); }
    std::string::const_iterator end() const   { return this->value_.end(); }
    std::string value_;
};

std::istream& operator>> (std::istream& in, token const& t)
{
    std::istreambuf_iterator<char> it(in >> std::ws), end;
    for (std::string::const_iterator sit(t.begin()), send(t.end());
         it != end && sit != send; ++it, ++sit) {
        if (*it != *sit) {
            in.setstate(std::ios_base::failbit);
            break;
        }
    }
    return in;
}

int main()
{
    std::istringstream input("age, (4, years, 5, months)\n"
                             "age , ( 8 , years , 7, months )\n"
                             "age, (4, year, 5, months)\n"
                             "age, (4, years 5, months)\n"
                             "age (4, years, 5, months)\n"
                             "age, 4, years, 5, months)\n"
                             "age, (4, years, 5, months)\n");
    std::string dummy;
    int         year, month;
    for (std::string line; std::getline(input, line); ) {
        std::istringstream lin(line);
        if (lin >> token("age") >> comma
            >> open
            >> year >> comma >> token("years") >> comma
            >> month >> comma >> token("months") >> close) {
            std::cout << "year=" << year << " month=" << month << "\n";
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM