题
我正在编写一个小程序供个人使用,以练习学习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. <www.win.com>. 4/29/09.
正如你所看到的,出现问题,因为我的输入被忽略了。
解决方案
这里发生的是 std :: cin&gt;&gt; firstName;
只读取但不包括第一个空格字符,当你按Enter键时,它包括换行符(或'\ n'
),所以当它到达 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"
添加' std :: cin&gt;&gt;在调用getline()修复问题之前,std :: ws
'( ws
意思是 w
hite s
pace): / p>
std::cin >> firstName >> std::ws;
getline(std::cin, articleTitle);
但是如果你在论证中这样做,你会更容易看到你错过了它:
std::cin >> firstName;
getline(std::cin >> std::ws, articleTitle);
其他提示
当您使用&gt;&gt;
运算符时, cin
会一直读到下一个空白字符,但它不会处理空格。所以,当你有
std::cin >> str1;
std::getline(std::cin, str2);
第二个调用将只处理换行符,您将无法输入任何输入。
相反,如果您计划在运算符&gt;&gt;
之后使用 getline
,则可以调用 std :: cin.ignore()
在致电 getline
之前吃掉换行符。
编辑:它可以按照您的预期工作
std::cin >> str1;
std::cin >> str2;
因为第二次调用将忽略所有前导空格。