0

ユーザーに整数を入力してもらいたいが、double または文字の値を入力したとします。ユーザーが正しい型を入力したことを確認するにはどうすればよいですか。

string line;
getline(cin, line);
// create stringstream object called lineStream for parsing:
stringstream lineStream(line); 
string rname;
double res;
int node1,node2;
lineStream >> rname >> res >> node1 >> node2;

有効な入力タイプを確認するにはどうすればよいですか?

4

3 に答える 3

1

ストリームが正常であることを確認します。

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
}
于 2013-09-28T15:52:02.267 に答える
0

最初に node1 と node2 を文字列に読み取ってから、正規表現で検証します。

#include <regex>
...
string node1_s, node2_s;
linestream >> rname >> node1_s >> node2_s
if (regex_match(node1_s, regex("[+-]?[0-9]+") {
    /* convert node1_s to int */
} else {
    /* node1_s not integer */
}
/* Do same for node2_s */
于 2013-09-28T16:27:23.870 に答える