无法在循环中读取Char/string

Unable to read Char/string in loop

本文关键字:Char string 读取 循环      更新时间:2023-10-16

这是一个非常简单的问题,一直困扰着我。在While循环中从一行中读取字符时,不会进行第二次读取。如果我使用cin>>name,它可以正常工作,但我需要字符之间的空格。使用String类也有同样的问题。

int main()
{
    int i=0;
    int intRate;
    char name[20];
    while(i!=3){
        cout<<"Enter name";
        gets(name);
        cout<<"Enter Interest Rate: ";
        cin>>intRate;
        i++;
        cout<<endl;
    }
    cout<<"name is : "<<name<<endl;
    cout<<"Interest Rate is: " <<intRate;
}

因此,当我尝试在循环中键入字符"gets(name)"时,第一次它接受该字符,然后我也可以输入intRate,但下次遇到循环i=1时,我不能为name键入任何内容,或者它不读取任何字符行,而是打印Enter Interest Rate,并在下面的循环中读取intRate

但如果我不输入输入利率线,那么它就会再次开始平稳读取,如下所示:

char name[20];
while(i!=3){
    cout<<"Enter name";
    i++;
    cout<<endl;

如果我这样做,它会读取循环中的所有字符。如果我在它下面再加一行打印,它就什么也看不出来了。

当您混合C和C++输入而不注意它们实际在做什么时,就会发生这种情况。

试试这个:

int main()
{
    int i = 0;
    int intRate = 0;
    string name;
    while (i != 3)
    {
        cout << "Enter name: ";
        getline(cin, name);
        cout << "Enter Interest Rate: ";
        cin >> intRate;
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), 'n');
        i++;
        cout << endl;
    }
    cout << "Name is : " << name << endl;
    cout << "Interest Rate is: " << intRate;
    return 0;
}

或者这个:

int main()
{
    int i = 0;
    int intRate = 0;
    string name, line;
    while (i != 3)
    {
        cout << "Enter name: ";
        getline(cin, name);
        cout << "Enter Interest Rate: ";
        getline(cin, line);
        stringstream ss(line);
        ss >> intRate;
        i++;
        cout << endl;
    }
    cout << "Name is : " << name << endl;
    cout << "Interest Rate is: " << intRate;
    return 0;
}
相关文章: