How can I make std::cin read spaces?(如何使std::CIN读取空格?)
本文介绍了如何使std::CIN读取空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道这个问题以前在这个网站上被问过一些,但我似乎不能掌握如何让它与我的特定程序一起工作。
本质上,我正在创建一个MadLibs类型的小游戏,玩家必须输入某些东西才能将其融入故事。现在,如果用户输入中没有空格,这种方法就可以很好地工作,但只要有人输入空格,程序就可以跳过整个问题。
以下是我的代码:
int main(){
int selection;
//News Report Variables
std::string nrfullname;
std::string nrcrime;
std::string nradjective;
std::string nrtown;
std::string nrpluralnoun;
std::string nrnounnotplace;
std::string nrverb;
std::string nradjective2;
std::string nrfullname2;
std::string nrnounnotplace2;
std::cout << "Welcome to Mad Libs! Please, pick a story!" << std::endl;
std::cout << "1. News Report" << std::endl;
std::cin >> selection;
if (selection == 1) {
std::cout << "We need a full name of someone." << std::endl;
std::cin >> nrfullname;
std::cout << "We need a crime." << std::endl;
std::cin >> nrcrime;
std::cout << "We need an adjective." << std::endl;
std::cin >> nradjective;
std::cout << "We need a town." << std::endl;
std::cin >> nrtown;
std::cout << "We need a plural noun." << std::endl;
std::cin >> nrpluralnoun;
std::cout << "We need a noun that is NOT a place." << std::endl;
std::cin >> nrnounnotplace;
std::cout << "We need a verb." << std::endl;
std::cin >> nrverb;
std::cout << "We need another adjective." << std::endl;
std::cin >> nradjective2;
std::cout << "We need a full name of someone else." << std::endl;
std::cin >> nrfullname2;
std::cout << "We need another noun that is NOT a place." << std::endl;
std::cin >> nrnounnotplace2;
}
正如您可能想象的那样,大多数人会选择在空格中输入某人的全名(我肯定我会这样做)。如果他们在空白处输入,它就会跳过犯罪问题,直接转到形容词问题。
如果您能告诉我如何让它正确工作,那将是有益的,因为它一直让我感到有点压力,而我尝试的所有解决方案要么使问题变得更糟,要么对解决它毫无帮助。
推荐答案
而不是std::cin >> nrfullname,您只需使用std::getline(std::cin, nrfullname [, delim])
std::getline()从输入流中提取字符并将结果存储在nrfullname中,直到下一个分隔符。如果不指定分隔符,则使用'
'。
这篇关于如何使std::CIN读取空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
编程基础网
本文标题为:如何使std::CIN读取空格?
基础教程推荐
猜你喜欢
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- c++ STL设置差异 2022-01-01
- 提升 ASIO 流缓冲 2021-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
