For 循环应该运行一次,但它没有运行
For Loop should run one time but it is not running
当我输入"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 之前和运算符>> 之后。
相关文章:
- 为什么无论你输入什么,这"while(cin.get(str,3))"只运行一次?
- 花括号使循环运行一次?
- 如何防止我的循环额外运行一次?
- 为什么循环只运行一次?
- 谷歌测试:如何为多个测试只运行一次夹具?
- CMAKE自定义目标仅运行一次
- Qt C++每秒运行一次代码
- 为什么我的函数中的这个 for 循环只会运行一次,即使它应该运行多次?
- 为什么我的fwrite命令只运行一次
- EXIT_SUCCESS和EXIT_FAILURE.它是在任何地方运行一次编译,还是在任何地方编写一次编译
- 是一个 for 循环,最终甚至不会运行一次,就像调用 if 语句以首先检查大小一样快
- C++,查找最低值,函数错误:循环最多运行一次(循环增量从未执行)
- 当循环应该只运行一次时,执行两次while循环(C++)
- C++循环最多运行一次
- 我的C++ Unity 插件在编辑器中运行一次,但不能运行两次
- C++:GetKeyState() 必须运行一次
- 如何使函数在程序的早期运行一次
- For 循环应该运行一次,但它没有运行
- 任务调度程序:从当前时刻开始,每小时运行一次任务
- 如何在没有外部标志的情况下只在循环中运行一次代码