我正在编写一个小程序供个人使用,用于练习学习C++及其功能,一个MLA引文生成器(我正在写一篇有几十次引用的大型论文).
由于缺乏更好的方法(我不懂课程或在你的主要内部使用其他.cpp文件,所以不要打扰告诉我,当我有更多时间时我会继续工作),我正在写作每种引用的功能.如果我有更多的时间,我可能会将其分解为每个重用代码的函数.
我的问题是:std :: cin对象是如何工作的?我目前正在使用std :: cin >>读取我希望成为单个单词的字符串,以及带有空格的字符串的getline(std :: cin,string).但是,我没有得到正确的输出.我只是想知道std :: cin如何工作以及为什么我会意外地跳过一些输入(例如,它跳过webPage而不是给我一个机会输入它).
void webCit() { std::cout << "Leave any unknowns blank.\n"; std::cout << "Author last name: "; std::string lastName; std::cin >> lastName; if (lastName.size() != 0) { lastName = lastName + ", "; } std::cout << "Author first name: "; std::string firstName; std::cin >> firstName; if (firstName.size() != 0) { firstName = firstName + ". "; } std::cout << "Article title: "; std::string articleTitle; getline(std::cin, articleTitle); if (articleTitle.size() != 0) { articleTitle = "\"" + articleTitle + ".\" "; } std::cout << "Title of web page: "; std::string pageTitle; std::cin >> pageTitle; if (pageTitle.size() != 0) { pageTitle = pageTitle + ". "; } std::cout << "Publication date: "; std::string publicationDate; getline(std::cin, publicationDate); if (publicationDate.size() != 0) { publicationDate = publicationDate + ". "; } std::cout << "Web address: "; std::string webAddress; getline(std::cin, webAddress); webAddress = "<" + webAddress + ">. "; std::cout << "Date accessed: "; std::string dateAccessed; getline(std::cin, dateAccessed); if (dateAccessed.size() != 0) { dateAccessed = dateAccessed + ". "; } std::string citation = lastName + firstName + articleTitle + pageTitle + publicationDate + webAddress + dateAccessed; std::cout << citation; //TEST; remove after }
编辑:I/O.
Leave any unknowns blank. Author last name: Hooked Author first name: Jerbear Article title: Title of web page: title Publication date: Web address: www.win.com Date accessed: 4/29/09 Hooked, Jerbear. Title.. 4/29/09.
正如你所看到的,出现问题,因为我的输入被忽略了.
这里发生的事情是std::cin >> firstName;
只读取但不包括第一个空白字符,'\n'
当你按Enter键时包含换行符(或),所以当它到达时getline(std::cin, articleTitle);
,'\n'
仍然是下一个字符std::cin
,并getline()
立即返回.
// cin = "Bloggs\nJoe\nMan of Steel, Woman of Kleenex\n" std::cin >> lastName; std::cin >> firstName; // firstName = "Joe", lastName = "Bloggs", cin = "\nMan of Steel, Woman of Kleenex\n" getline(std::cin, articleTitle); // articleTitle = "", cin = "Man of Steel, Woman of Kleenex\n"
在调用getline()之前添加' std::cin >> std::ws
'(ws
意思是w
hite s
pace)可以解决问题:
std::cin >> firstName >> std::ws; getline(std::cin, articleTitle);
但是如果你在论证中这样做,你会更容易看到你错过了它:
std::cin >> firstName; getline(std::cin >> std::ws, articleTitle);