cin.getline()循环内出现问题。

huangapple go评论64阅读模式
英文:

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 &lt;iostream&gt;
using namespace std;

main()
{
	char name[3][11];
	
	for(int i=0;i&lt;3;i++)
	{
		cin.getline(name[i],10,&#39;\n&#39;);
	}
	
}

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 &lt;iostream&gt;
using namespace std;

main()
{
	char name[3][11];
	
	for(int i=0;i&lt;3;i++)
	{
		cin.ignore(256,&#39;\n&#39;);
		cin.getline(name[i],10,&#39;\n&#39;);
	}
	
}

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 &lt;iostream&gt;
#include &lt;string&gt;
using namespace std;

int main()
{
    string name[3];
    
    for(int i=0;i&lt;3;i++)
    {
        getline(cin, name[i]);
    }    
}

huangapple
  • 本文由 发表于 2023年2月27日 00:22:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/75573353.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定