【问题标题】:C++ reading from stdin using istringstreamC++ 使用 istringstream 从标准输入读取
【发布时间】:2016-04-10 17:12:34
【问题描述】:

我试图从键盘调用不同的功能,但由于我对 cin、istringstream 等缺乏知识/经验,我遇到了一些问题。这是我的简化代码:

#include <iostream>
#include <sstream>

using namespace std;

int main(int argc,char **argv) {

    string line;
    do {
        getline(cin,line);
        istringstream iss(line);
        string word;
        iss >> word;
        if (word ==  "function") {
            int id;
            if (!(iss >> id)) {
                cout << "Not integer.Try again" << endl;
                continue;
            }
            cout << id << endl;
            iss >> word;
            cout << word << endl;
        }
        else cout << "No such function found.Try again!" << endl;
    } while (!cin.eof());

    cout << "Program Terminated" << endl;
    return 0;
}

我目前处理的两个问题是:

• 为什么在检查我是否得到一个整数后,当我键入不是整数的内容时,do-while 循环会终止? (例如“function dw25”)-必须使用 continue;而不是 break;。认为 break 会退出外部 if 条件。

• 由于我不想得到 id == 25 & word == dwa,我如何解决键入“function 25dwa”时出现的问题。

【问题讨论】:

  • do-while 循环终止的原因是因为你使用的是 break .if (!(iss >> id)) {cout 休息; }
  • 是的,我自己想通了并编辑了我的帖子。谢谢你。仍在尝试为第二个问题寻找解决方案或解决方法
  • 用 continue 替换 break 并阅读解析器。

标签: c++ stdin cin eof istringstream


【解决方案1】:

我认为您可以使用strtol 来检查 id 是否为整数。

#include <iostream>
#include <sstream>
#include <stdlib.h>

using namespace std;

int main()
{
    string word, value;
    while ((cin >> word >> value)) {
        if (word == "function") {
            char* e;
            int id = (int) strtol(value.c_str(), &e, 10);
            if (*e) {
                cout << "Not integer.Try again" << endl;
                break;
            }
            cout << id << endl;
            if (!(cin >> word))
                break;

            cout << word << endl;
        } else {
            cout << "No such function found.Try again!" << endl;
        }
    }

    cout << "Program Terminated" << endl;
    return 0;
}

【讨论】: