如果cin不是整数则停止无限循环

当我在cin输入一个字符串值时,它将进入无限循环。您能帮我解决此问题,以便当我输入字母值时退出程序。 这是我的代码:

#include <iostream>
#include <fstream> //create,write and read files 
#include <string>
using namespace std; 

struct bloc { //structure called bloc 
    int age;
}; 

int writeData(ofstream &os,struct bloc b) { 
    os << "Age: " << b.age << endl; 
    return 1;
 }

int main(){
    //declare again variable of struct 
    int age; 

    cout<<"\n**** To finish the user prompting,press any character ****"<<endl;

    const int LIMIT=21; //max size 
    char filename[LIMIT]={"fileE3.txt"}; //create file 

    //open file for reading 
    ofstream os; 
    os.open(filename,ios::out);

    struct bloc b;
    int cnt=0;

    while(true){
        cout<<"Age : ";
        cin>>b.age;
        cout<<endl; 
        cin.ignore(3,'\n');

        int num=writeData(os,b);
        cnt+=num;
        cout<<"fwrite returned :"<<num<<endl;
        cout<<"Total records written into the file is :"<<cnt<<endl;     
    }
    os.close();    
    system("close");

    return 0;
}

您的帮助将不胜感激。谢谢。

lshongbo 回答:如果cin不是整数则停止无限循环

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/3085080.html

大家都在问