请问C++中skipws、ws两者有什么区别?

2026年09月24日 04:33
有1个网友回答
网友(1):

skipws的意思是在用>>读取数据之前跳过空格(此时空格依然存在),ws的意思是读取后面的所有空格(空格被跳过)。下面是个示例,你可以揣摩一下:

#include 
#include 
#include 
using namespace std;

int main(){
    istringstream istr(" 123 - 123");
    int a;
    istr >> noskipws >> a;
    if (!istr){
        cerr << "读取错误\n";
        istr.clear();
    }
    istr >> skipws >> a;
    cout << "a = " << a << "\n";
    char c;
    if (istr.get(c), c != '-'){
        cerr << "不是-\n";
        istr.unget();
    }
    if ((istr >> ws).get(c), c == '-'){
        istr >> a;
        cout << "a = " << a << "\n";
    }

    return 0;
}