C++ 退出while循环后最后一个输入不工作

C++ 退出while循环后最后一个输入不工作,c++,C++,只是好奇如何解决cin的这个小问题 int main(){ int x,w; while(cin>>x){ cout<<"This is x -> " << x << endl; } //now this cin will not be executed cin>> w; cout<< "This is w ->

只是好奇如何解决cin的这个小问题

int main(){

    int x,w;
    while(cin>>x){
         cout<<"This is x -> " << x << endl;
    }

    //now this cin will not be executed

    cin>> w;

    cout<< "This is w -> "<< w << endl;

    //prints some garbage value for w

}
intmain(){
int x,w;
而(cin>>x){

cout当您通过输入错误的数据类型(非数字输入)退出
时,您需要从流中删除无效的输入。您可以这样做:

while(cin >> x){
    cout << "This is x -> " << x << endl;
}

std::cin.clear();
std::string str;
// read the invalid input from stream in some string 'str'
std::getline(std::cin, a);

// now you can take input normally
std::cin >> w;
while(cin>>x){

While
循环终止时,您会得到垃圾值,因为您必须清除无效的输入流,然后在从用户获取另一个值之前读取标准输入。我为您做了一些事情。我想这可能会对您有所帮助

int main() 
   {
    int x, w;
    while (cin >> x)
    {
        cout << "This is x -> " << x << endl;
    }

    cin.clear();  //removing the invalid input from the stream
    getchar();    //reads from standard input
    cout << "Enter w : " << ' ';
    cin >> w;
    cout << "This is w -> " << w << endl;
    return 0;
}

谢谢!似乎有效。但是,当我运行“echo{1..10}|./filename”时,垃圾值返回。
5
This is x -> 5
4
This is x -> 4
3
This is x -> 3
t

Enter w :  10
This is w -> 10