ストリームが正常であることを確認します。
if (lineStream >> rname >> res >> node1 >> node2)
{
// all reads worked.
}
最後にゴミをチェックしたいかもしれません。
if (lineStream >> rname >> res >> node1 >> node2)
{
char x;
if (lineStream >> x)
{
// If you can read one more character there is junk on the end.
// This is probably an error. So in this situation you
// need to do somethings to correct for this.
exit(1);
}
// all reads worked.
// AND there is no junk on the end of the line.
}
コメント展開。
以下のコメントから:
rname に整数を入力しても機能します。例:
string line; getline(cin, line);
stringstream lineStream(line); // created stringstream object called lineStream for parsing
string rname;
if (lineStream >> rname) { cout << "works"; }
rname
それについていくつかのプロパティがあり、それを数値と区別できると仮定しましょう。例: 名前でなければなりません。つまり、英字のみを含める必要があります。
struct Name
{
std::string value;
friend std::istream& operator>>(std::istream& s, Name& data)
{
// Read a word
s >> data.value;
// Check to make sure that value is only alpha()
if (find_if(data.value.begin(), data.value.end(), [](char c){return !isalpha(c);}) != str.end())
{
// failure is set in the stream.
s.setstate(std::ios::failbit);
}
// return the stream
return s;
}
};
これで名前が読めるようになりました。
Name rname;
if (lineStream >> rname) { cout << "works"; }
rname に整数を入力すると、これは失敗します。
ストレッチアンサー
読みたい同じ情報が複数行ある場合。次に、それをクラスにラップして、入力ストリーム演算子を定義する価値があります。
strcut Node
{
Name rname;
double res;
int node1;
int node2;
friend std::istream& operator>>(std::istream& s, Node& data)
{
std::string line;
std::getline(s, line);
std::stringstream linestream(line);
lineStream >> data.rname >> data.res >> data.node1 >> data.node2;
if(!linestream)
{
// Read failed.
s.setstate(std::ios::failbit);
}
return s;
}
};
これで、ループ内の行が読みやすくなりました。
Node n;
while(std::cin >> n)
{
// We read another node successfully
}