Использование getline (cin, s) после cin
Мне нужна следующая программа, чтобы взять всю строку ввода пользователя и поместить ее в имена строк:
Если команда cin >> number перед командой getline() (что я предполагаю, это проблема), она не позволит мне вводить имена. Почему?
Я слышал что-то о команде cin.clear() , но я понятия не имею, как это работает или почему это даже необходимо.
12 ответов
В приведенном выше коде этот бит.
. проверяет остальную строку ввода после того, как число содержит только пробелы.
Почему бы просто не использовать ignore?
Это довольно многословно, поэтому использование ignore в потоке после >> x является часто рекомендуемым альтернативным способом отбрасывания содержимого до следующей новой строки, но он рискует выбросить не-пробельный контент и при этом игнорировать поврежденные данные в файле. Вы можете или не должны заботиться, в зависимости от того, доверено ли содержимое файла, насколько важно избегать обработки поврежденных данных и т.д.
Итак, когда вы будете использовать clear и игнорировать?
Итак, std::cin.clear() (и std::cin.igore() ) для этого не требуется, но полезно для удаления состояния ошибки. Например, если вы хотите дать пользователю много шансов ввести действительный номер.
Не может быть проще с skipws или схожим?
Другая простая, но наполовину испеченная альтернатива ignore для вашего первоначального требования — использовать std::skipws , чтобы пропустить любое количество пробелов перед чтением строк.
. но если он вводится как «1E6» (например, какой-то ученый пытается ввести 1 000 000, но С++ поддерживает только эту нотацию для чисел с плавающей запятой) не согласится с тем, что вы закончите с помощью number set до 1 и E6 считать первым значением name . Отдельно, если у вас есть действительное число, за которым следуют одна или несколько пустых строк, эти строки будут игнорироваться.
Почему getline не работает после cin c
Return to Topic Menu | Computer Science Main Page | MathBits.com | Terms of Use
| Problems with getline(cin, name); |
Since getline does not ignore leading whitespace characters, you should take special care when using it in conjunction with cin >> .
The problem: cin>> leaves the newline character (\n) in the iostream. If getline is used after cin>> , the getline sees this newline character as leading whitespace, thinks it is finished and stops reading any further.
Program fragment with problem:
apstring name;
int age;
Enter your age 5
Enter your full name Ben Bunny
, you are 5
The yellow wave is the iostream. The cin statement uses the 5 and leaves the \n in the stream as garbage. The cin statement will NOT read (or "grab") \n. The cin also ignores \n when reading data. The getline, on the other hand, reads and "grabs" \n. So, when it sees the \n LEFT from cin, it "grabs" the \n and thinks it is finished reading.
Don’t be a dumb bunny and fall for this trap.
Ways to fix the problem:
Consume the trailing newline character from the cin>> before calling getline, by "grabbing" it and putting it into a "dummy" variable.
You will see me using this method throughout the course.
apstring dummy;
getline(cin, dummy);
Program fragment with correction:
apstring name, dummy;
int age;
cout<<"Enter your age";
cin>>age;
getline(cin,dummy);
cout<<"Enter your full name";
getline(cin, name);
Enter your age 5
Enter your full name Ben Bunny
Ben Bunny, you are 5
Не выполняется функция getline()
cin.getline() не выполняется
В коде ниже не выполняется cin.getline(), просто пропускает и начинает выполнять следующую строку.
Функция getline
Добрый вечер. Очень долго пытался найти в чём проблема в работе программы-она выдавала немного не.
Функция getline
Делаю упражнение по С++ (консольное приложение). Необходимо считать строку, включая пробелы. Вот.
How to Avoid Issues With Mixing cin >> and getline() In C++
![]()
Learning how to create programs in C++ can be confusing at first, and one of the concepts I struggled with as a beginner was figuring out how C++ handles user input. I would encounter issues where my program seemed to simply refuse to collect user input the way that I wanted it to. If you’re mixing cin >> and getline() together, there’s a good chance you may be encountering similar issues as I did. It’s important to remember that there’s always an explanation for why computers act the way they do, even if it doesn’t seem like it at times. Once you understand how cin >> and getline() work, you can understand why these issues occur and how to fix them.
When collecting user input in a C++ program, it is important to understand exactly how the input is being collected so you can identify the source of issues when they arise. Two ways of obtaining user input in C++ are using cin along with the stream extraction operator— the >> symbol— and getline(). It’s important to know that these two ways of collecting input don’t collect input the same way. Here’s an example of the issues that may occur when you mix the two:
If you run this program, you will only be able to enter your first input before the program prints out what you entered, even though there’s supposed to be two inputs. Why does this occur? It has to do with the differences between how cin >> and getline() work. By understanding how each one functions, you can learn how to avoid this issue and make informed decisions about when to use cin >> and when to use getline().
Using cin with the stream extraction operator will collect user input from the input buffer until it encounters whitespace, such as a space or a newline character, or until it encounters a character that isn’t valid for the data type it’s trying to collect. For example, this can occur if there is a letter in the input buffer when the program is looking for an integer. You can think of the input buffer as a box where user input is temporarily stored until the program collects it. The first characters typed are collected first, and whatever you type last is stored at the end. However, cin >> isn’t the best way to collect input if you want to collect entire lines of input.
getline() is a function that takes two parameters: an input stream and the string variable that the input should be stored in. Optionally, you can use a third parameter to specify the delimiter character. By default, this is the newline character. Unlike using cin with the stream extraction operator, getline will collect input until it reaches the delimiter character, which will then be discarded. You can find a detailed explanation of how getline() works here. getline() works best when you want to collect entire lines of input as opposed to individual words or numbers.
Issues can sometimes occur when mixing these two methods of obtaining input. A newline character could be left in the input buffer, which then gets collected instead of the intended data. This might cause the variable to appear empty when outputting the data to figure out where a bug is coming from. If you ran the example program above, you may have noticed that there seems to be an extra line printed at the end of the program; this is because secondInput had a newline character stored in it. Fortunately, there are easy ways to deal with this remaining newline character.
There are two ways that the extra newline character can be dealt with. I try to avoid mixing cin >> and getline() when I can, so that this issue is prevented from popping up in the first place. If you must use cin >> and getline() together, you can use cin.ignore() to get rid of the remaining newline character in the input buffer. Here’s an example program that demonstrates how this solution works:
This program properly takes two inputs are prints them out at the end of the program. cin.ignore() will remove the remaining characters that are still in the input buffer after collecting the first input. It makes sure that no extra newline characters are stuck inside of the input buffer when getline() goes to ask for the second input. Now both inputs can be collected without accidentally grabbing a newline character instead.
If you’re experiencing issues with your program, it’s a good idea to check that the program is actually collecting input the way that you expect it to. Incorrect input can easily lead to strange issues later on in a program’s execution; a program cannot be expected to produce the correct output if the input is incorrect. Only move to inspecting the rest of your program once you are absolutely certain that your input is being collected correctly. If you know your input is correct, then that’s one less part of your program to check for bugs.