簡體   English   中英

使用istringstream從stdin讀取C ++

[英]C++ reading from stdin using istringstream

我試圖從鍵盤調用不同的功能,但是由於缺乏對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”) -必須繼續使用; 思維中斷將退出外部if條件。

•我不想輸入id == 25&word == dwa時,如何解決鍵入“ function 25dwa”時出現的問題。

我認為您可以使用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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM