C ++-以字母和数字序列读取int

int number;
string text;

cin>>number;          // Here I read "1234aaaa"
cin>>text;

cout<<number<<" "<<text;      // It prints "1234 aaaa"

I understand that the stream stores aaaa from the previous reading and then it passes it to the next reading.

How can I avoid the garbage value from number to be passed to text ?

评论
  • wet
    wet 回复

    您可以使用临时字符串来消耗所有输入,然后进行转换

    int number;
    string text;
    string tmp;
    
    cin>>tmp;          // Here I read "1234aaaa"
    number = atoi(tmp.data());
    cin>>text;
    
    cout<<number<<" "<<text; 
    
  • miste
    miste 回复
    如何避免数字中的垃圾值传递给文本?

    if you want to flush all the rest of the line after the number you can use getline or

    cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');