C++ 使用 istringstream 从 stdin 读取

标签 c++ stdin cin eof 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”)-必须使用 continue;而不是 break;.Thought break 会退出外部 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;
}

关于C++ 使用 istringstream 从 stdin 读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36532876/

相关文章:

c++ - 在析构函数中调用 CloseHandle 会导致运行时内存错误,如何正确关闭结构/类中的文件句柄?

c++ - 为什么在选择排序中使用 Xor 运算符交换对象不起作用?

c - Scanf 字符串空间问题 C

c++ - printf ("something\n") 输出 "something "(附加空间) (g++/linux/用gedit读取输出文件)

C 程序在 if/else 之后终止,或者如果我使用 fputs/fgets 则重复

c++ - 在 QtCreator 中使用 cin

c++ - gcc/g++ 可以在忽略我的寄存器时告诉我吗?

c++ - 如何在 Ubuntu 中使用 Eclipse CDT 调试 C++ 静态库?

c++ - 如何在不按 ENTER 且不使用 getch() 或 getche() 的情况下读取 C++ 中的字符?

c++ - 多用户输入选择 C++