1

我希望能够阅读以下内容:

myvar = { 1 2 3 5 }

所以我所做的是

string input;
int intInput;

cin >> input; //take in the varname, do stuff
cin >> input; // check to make sure it's "="
if (input != "=") {
    //stuff
}

cin >> input; //check to make sure it's "{"
if (input != "{") {
    //stuff
}

while (cin >> intInput) {
   //stuff
   cout << intInput << endl;
}

至此,我的理解是“}”这个char已经存入了intInput,结束了while循环。我想确保它以“}”结尾。

c.unget();
cin >> input;
if (input != "}") {
    //stuff
} 

我以为 c.unget(); 会给我最后一个字符,在这种情况下是“}”,但是当我计算输入值时,输入仍然是“{”。

如何确保集合以“}”字符结尾?

4

5 回答 5

2

如果您 cout 输入,您将得到一个“{”,因为它是它在此处读取的最后一个字符串:

cin >> input; //check to make sure it's "{"

然后你将你的数字放入 intInput。您可以一直使用字符串读取输入,如果不等于“}”,则将其转换为整数

#include <cstdlib>
while (cin >> input) {
    if(input == "}")
        break;
    else
       intInput = atoi(input.c_str()); //or whatever means you prefer to convert a string to int
    cout << intInput << endl;
}

如果读取了“}”,它就会跳出你的循环。

于 2013-03-10T21:53:38.373 回答
1
#include <iostream>
#include <sstream>
using namespace std;
int main() {
    string name, buf;
    cin >> name;
    cin >> buf; // =
    cin >> buf; // {
    while(1) {
        if(cin >> buf) {
            if(buf == "}") break;
            stringstream ss(buf);
            int i;
            ss >> i;
            if(ss.fail()) {
                cout << "fail" << endl;
                            //conversion error
            } else {
                cout << i << endl;
            }
        } else {
            cout << "no }" << endl;
                    break;
            //only if cin is reading from file, or wating for CTRL+D from terminal emulator
        }

    }

}
于 2013-03-10T21:56:17.573 回答
1

看一下这个:

#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
    int i;
    string input;
    while (cin >> input)
    {
        if (input == "}")
            break;
        else
            stringstream(input) >> i;

        cout << i << endl;
    }
}
于 2013-03-10T21:57:23.743 回答
0

我会读到 std::string 并检查它是数字还是“}”符号

while (cin >> stringInput) {
    if (stringInput = "}") {
        break;
    }
    if (sscanf(stringInput.c_str(), "%d", &intInput) == 0) {
         //stuff
    }
}

不过,使用/编写词法分析器可能会更好

于 2013-03-10T21:53:47.930 回答
0

如果不是数字,缓冲区仍将包含用户输入的字符。它只会设置失败标志。只需再次作为字符串读取:

string input;
int intInput;

cin >> input; //take in the varname, do stuff
cin >> input; // check to make sure it's "="
if (input != "=") {
    //stuff
}

cin >> input; //check to make sure it's "{"
if (input != "{") {
    //stuff
}

do {
   cin >> int;
   if (!cin) {
       cin.clear();    // clear error flags
       cin >> input;   // read again as string
       if (input != "}") {
           // handle error
       }
   }
   else
       cout << intInput << endl;
} while (input != "}");
于 2013-03-10T22:06:55.307 回答