简体   繁体   English

当我超过第一个getline()输入中的数组大小时,第二个getline或其他输入函数不起作用

[英]second getline or other input functions doesnt work when i exceed the array size in input for first getline()

#include <iostream> 
#include <string.h>
#include<stdio.h>
using namespace std;

int main() 
{
char d,a[9],e[9];

cin.getline(a,9);
cin.getline(e,9);
cin>>d;
puts(a);
puts(e);
cout<<d<<endl;
return 0}

when i enter "hey every one" on the output screen, puts(e) prints a blank line and d prints a random character.second getline function and cin function is not working because of first getline . 当我在输出屏幕上输入“hey every one”时, puts(e)打印一个空白行并且d打印一个随机字符。第二个getline函数和cin函数由于第一个getline而无效。 Thanks in advance. 提前致谢。

You should read some documentation for the stuff you use: 你应该阅读一些你使用的东西的文档

After constructing and checking the sentry object, extracts characters from *this and stores them in successive locations of the array whose first element is pointed to by s, until any of the following occurs (tested in the order shown): 在构造和检查sentry对象之后,从* this中提取字符并将它们存储在第一个元素由s指向的数组的连续位置,直到出现以下任何一个(按所示顺序测试):
- [...] - [...]
- count-1 characters have been extracted ( in which case setstate(failbit) is executed ). - 已提取count-1个字符( 在这种情况下执行setstate(failbit) )。

(Emphasize mine) (强调我的)

So the first getline fails if the input is too long and thus leaves std::cin in a bad (ie unreadable) state. 因此,如果输入太长,第一个getline失败,从而使std::cin处于不良(即不可读)的状态。 This makes all successive input operations fail immediately. 这使得所有连续输入操作立即失败。


Remark: To avoid tons of ugly trouble, you should avoid using C-style strings and the "kind of C-style" member- getline and just use std::string and the non-member std::getline instead. 备注:为了避免大量的丑陋麻烦,你应该避免使用C风格的字符串和“C风格的”成员 - getline ,只需使用std::string和非成员std::getline

When you use 当你使用

cin.getline(); cin.getline();

and when you press Enter after entering the string, that enter goes into the next string. 当您在输入字符串后按Enter键时,该输入将进入下一个字符串。

In order to prevent it, use cin.ignore(); 为了防止它,使用cin.ignore();

It ignores the Enter and prevents it from entering into another string. 它会忽略Enter并阻止它进入另一个字符串。

Here is your modified code: 这是您修改后的代码:

#include<iostream> 
#include <cstring>
using namespace std;

int main() 
{
char d,a[9],e[9];
cout<<"String:"<<endl;
cin.getline(a,9);
cin.ignore();
cout<<"String:"<<endl;
cin.getline(e,9);

cin>>d;
cout<<a;
cout<<e;
cout<<d<<endl;
return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM