从控制台读取字符串以及空格
Read string from console along with whitespaces
我想从cin中读取一个字符串,直到按下返回键。下面的代码出了什么问题?输出重复显示"发现无效响应,请再次输入:"即使我输入单个单词。。我已经更新了代码。。
int readInt() {
int num;
while (!(std::cin >> num)) {
std::cout << "Invalid response found, please enter again: ";
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
}
return num;
}
string readString() {
string str;
while (std::getline(std::cin, str) && std::cin.fail()) {
std::cout << "Invalid response found, please enter again: ";
std::cin.clear();
std::cin.ignore();
}
return str;
}
DVD_Node* addNewDvd(DVD_Node *head) {
DVD_Node* temp = new DVD_Node;
int new_id = getNewID(head);
temp->id = new_id;
cout << "nn-- Add a new DVD to your collection --";
cout << "nnEnter movie name: ";
temp->title = readString();
cout << "nnEnter duration in minutes: ";
temp->duration = readInt();
cout << "nnEnter movie year: ";
temp->year = readInt();
cout << "nnEnter movie actor 1 name: ";
temp->actor1 = readString();
cout << "nnEnter movie actor 2 name: ";
temp->actor2 = readString();
temp->next = head;
changes_remaining = 1;
cout << "nnYour DVD Data has been added successfully.";
return temp;
}
如果您想检测错误,下面的测试是不正确的:
std::getline(std::cin, str) && std::cin.fail()
事实上,因为getline
返回输入,所以您希望检测空输入或错误:
std::getline(std::cin, str) == 0 || std::cin.fail()
相关文章:
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- 移除前面有空格的前2个字符串
- 用于存储由空格分隔的字符串的 C++/C 数据结构
- 在字符串中插入空格
- C ++中的StringStream有助于使用向量从字符串中提取逗号分隔的整数,而不是空格分隔的整数,为什么?
- 使用另一个字符串从字符串中删除空格
- 我还可以添加什么来按空格或空格正确拆分C++字符串?
- C++ "noskipws"没有按预期工作,如何正确允许字符串中的空格?
- 在 c++ 中逐行阅读字符串,不要以空格停止
- std::regex:匹配由数字和空格组成的字符串,并提取数字.如何?
- 如何存储包含多个空格的字符串 c++
- 在特定位置为字符串添加空格
- 有没有办法在 c++ 中获取带有空格的完整字符串?
- C++完全复制要字符串的字符列表,而不会忽略多个空格
- Winsock2:当我尝试发送带有空格的字符串时,该函数在遇到空格时似乎停止发送
- 从没有空格的字符串中提取整数
- 用于拆分空格字符串的程序不起作用
- 解析C++中的完整(从头到尾)字符串,包括所有空格
- 反转字符串中单词的位置,而不更改 O(1) 空格限制中特殊字符的顺序
- 如何获取我的区域设置的空格字符串?