英文:
Problem with cin.getline() inside of a loop
问题
以下是您要求的代码的翻译部分:
#include <iostream>
using namespace std;
int main()
{
char name[3][11];
for (int i = 0; i < 3; i++)
{
cin.getline(name[i], 10, '\n');
}
}
您尝试使用fflush(stdin)
,cin.get()
,cin.ignore
等方法,但没有奏效。您想要输入任意数量的字符,但只获取其中的十个字符。
以下是您尝试的代码的翻译部分:
#include <iostream>
using namespace std;
int main()
{
char name[3][11];
for (int i = 0; i < 3; i++)
{
cin.ignore(256, '\n');
cin.getline(name[i], 10, '\n');
}
}
您提到已经阅读了很多类似的问题,但找不到解决方案。
英文:
The loop works well as long as it enters less than 10 characters as an option, but if I enter more simply ignore the cin.getline.
#include <iostream>
using namespace std;
main()
{
char name[3][11];
for(int i=0;i<3;i++)
{
cin.getline(name[i],10,'\n');
}
}
i tried with fflush(stdin)
,cin.get()
,cin.ignore
but doesnt work, I want to enter a string of any amount of characters and only take ten.
An example of what I did to try:
#include <iostream>
using namespace std;
main()
{
char name[3][11];
for(int i=0;i<3;i++)
{
cin.ignore(256,'\n');
cin.getline(name[i],10,'\n');
}
}
I really read a lot of problems like this, but I cant´t find a solution.
答案1
得分: 1
如果输入超过char[]
数组的容量,cin.getline()
会在cin
流上设置failbit
。在这种情况下,你需要调用cin.clear()
来重置流的错误状态,然后才能继续从流中读取。
由于你事先不知道用户输入的大小,你应该使用std::string
而不是char[]
,因为std::string
可以随着输入的读取而增大,例如:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string name[3];
for(int i=0; i<3; i++)
{
getline(cin, name[i]);
}
}
英文:
If the input is larger than the char[]
array can hold, cin.getline()
will set the failbit
on the cin
stream. In which case, you would need to call cin.clear()
to reset the stream's error state before you can continue reading from the stream again.
Since you don't know the size of the user's input ahead of time, you should be using std::string
instead of char[]
, as std::string
can grow in size as input is read into it, eg:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string name[3];
for(int i=0;i<3;i++)
{
getline(cin, name[i]);
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论