我正在写一个小程序供我个人使用,练习学习C++及其功能,一个MLA引用生成器(我正在写一篇带有数十次引用的大型论文)。因为缺乏更好的方法来做到这一点(我不明白类或在你的主内部使用其他.cpp文件,所以不要打扰告诉我,当我有更多的时间,我会努力) ,我正在为每种引用类型写一个函数。如果我获得更多时间,我可能会将其分解为每个重用代码的函数。C++中std :: cin对象的规则是什么?
我的问题是:std :: cin对象是如何工作的?我目前正在用std :: cin >>读取字符串,我希望这些字符串是单个字符,而getline(std :: cin,字符串)则是空格字符串。虽然我没有得到正确的输出结果。我只想知道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.
正如你所看到的,事情错了,因为我的投入是越来越跳过。
我没有看到任何明显的问题,你这样做...你可以复制和粘贴你的交互t他的计划,你有什么确切的投入和产出? 此外,我会建议把“使用名称空间标准;”在顶部(通常在所有的#include的后面),这样你就可以说“cin”和“cout”,而不必一次又一次地写std ::。但是,当然......无论如何你都不必这样。 – MatrixFrog 2009-04-30 05:28:07
我添加了一些I/O。 – jkeys 2009-04-30 05:33:46
@MatrixFrog:我更喜欢`使用std :: cin;使用std :: cout; ...`,或者在使用它的函数内部使用`namespace std;`,而不是在全局级别。 – 2009-04-30 05:50:54