use*_*986 0 c++ strtok istringstream
我有以下代码使用strtok接收来自txt文件的输入.txt文件中的输入是:
age, (4, years, 5, months)
age, (8, years, 7, months)
age, (4, years, 5, months)
Run Code Online (Sandbox Code Playgroud)
我的代码看起来像:
char * point;
ifstream file;
file.open(file.c_str());
if(file.is_open())
{
while(file.good())
{
getline(file, take);
point = strtok(&take[0], ", ()");
}
}
Run Code Online (Sandbox Code Playgroud)
除了第2年龄和第3年龄的输出缺失外,它一切正常.谁能告诉我他们为什么失踪?
我也试过,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,", ()");
}
}
Run Code Online (Sandbox Code Playgroud)
就个人而言,我会使用一个,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";
}
}
}
Run Code Online (Sandbox Code Playgroud)