For 循环应该运行一次,但它没有运行

For Loop should run one time but it is not running

本文关键字:运行 一次 循环 For      更新时间:2023-10-16

当我输入"1"时,for 循环应该运行一次。 但它只打印"0"。我不知道为什么。我认为问题出在"getline(cin,input)"上,但我不知道问题所在。这是代码:

int main()
{
    string input;
    int t, output, occured_length, lenght, match;
    char occured[26];
    cin>>t;
    for(int i=0; i<t; i++)   //I am talking about this loop
    {
        occured_length = 0;
        getline(cin, input);   //This might be causing the problem
        lenght = input.size();
        for(int j=0; j<lenght; j++)
        {
            if(occured_length == 25)
            {
                cout<<"n"<<occured_length+1;
                break;
            }
            match = 0;
            for(int k=0; k<occured_length; k++)
            {
                if(input[j] == occured[k])
                {
                    match= 1;
                    break;
                }
            }
            if(match == 0)
            {
                occured_length++;
                occured[occured_length] = input[i];
            }
        }
        cout<<"n"<<occured_length;
    }
    return 0;
}
输入

为空,长度为 0

istream& getline (istream& is, string& str);

获取从输入流到字符串的行。它从 is 中提取字符并将它们存储到 str 中,直到找到换行符 ''。 保留在输入流中,您需要另一个虚拟输入读取,否则您将在下一个 getline 上得到 input = "

cin>>t; 
char c;
cin >> c;

问题是输入后使用 operator >>

cin>>t;

输入缓冲区将包含换行符。和下一个语句与getline

getline(cin, input);

读取空字符串。

您必须从输入缓冲区 usig 方法忽略中删除换行符。例如

#include <limits>
//...

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

忽略的调用应该在 getline 之前和运算符>> 之后。