[英]What is this cin.getline() behaviour?
我不是在尋找替代方案,只是想了解為什么C ++會這樣做。
char name [25];
cin.getline(name,25);
例如,如果我超過了getline的'25'輸入限制,為什么它會這樣做但是沖過程序,它不會停止任何cin.get(),它是否與failbit標志有關?
#include <iostream>
#include <cstring> // for the strlen() function
using namespace std;
int main()
{
char defName[25];
char name[25];
for (int x = 0; x < 25; x++)
{
if (x != 24)
defName[x] = 'x';
else
defName[x] = '\0';
}
cout << "Default Name: " << defName << endl << endl;
cout << "Please enter a name to feed into the placeholder (24 Char max): ";
cin.getline(name, 25);
name[24] = '\0';
cout << "You typed " << name << endl;
cin.get();
for (int i = 0; i < strlen(name); i++)
if (name[i] != ' ')
{
{
defName[i] = name[i];
}
}
cout << "Placeholder: " << defName;
cin.get();
return 0;
}
它與failbit標志有關嗎?
實際上,如果輸入對於緩沖區來說太長,則設置failbit
。 你可以檢查一下:
if (!cin.getline(name, 25)) {
cout << "Too long!\n";
}
並且,如果你想繼續,用cin.clear()
清除它,並用cin.ignore(-1)
刪除未讀的字符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.