如何输入“代码项目"之类的字符串?到使用istream的字符串类型? [英] How to input a string like "The code Project" to a string type using istream?
本文介绍了如何输入“代码项目"之类的字符串?到使用istream的字符串类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
大家好,
我的问题是,当我尝试输入书名时,我不会成功,代码如下:
Hi guys,
my problem is when I was trying to enter a book name, I won''t success, codes like below:
class SalseItem
{
friend istream& operator>>(istream& is,SalseItem& si){
cout<<"Please input the book name:"<<endl;
is>>si.name;
cout<<"Please input the number:"<<endl;
is>>si.num;
cout<<"Please enter the price:"<<endl;
is>>si.price;
if(!is)
si = SalesItem();//default constructor
return is;
}
...
}
int main(int argc, char* argv[])
{
SalseItem si;
cin>>si;//I enter "The code project" + key_return,then si.name == "The" ,not "The code project";
cout<<si;
return 0;
}
我如何通过将代码项目"准确输入到si.name中来完成这项工作?
[edit]删除了伪代码块-OriginalGriff [/edit]
How can I achieve the job ,inputing exactly "The code project" to a si.name?
[edit]Spurious code blocks removed - OriginalGriff[/edit]
推荐答案
如果您查看 ^ ],您将看到问题:
当下一个字符为有效空格或空字符,或者到达文件末尾时,提取结束."
您可能要使用 getline [
If you look at the definition for istream>>[^], you will see the problem:
"Extraction ends when the next character is either a valid whitespace or a null character, or if the End-Of-File is reached."
You may want to use getline[^] instead.
当您写入is>>si.name;
cin
时,一旦发现任何空格字符,提取就会停止读取.
为了获得整行,请使用功能getline
:
Hi,
When you writeis>>si.name;
cin
extraction stops reading as soon as it finds any blank space character.
In order to get entire lines, use the functiongetline
:
class SalseItem
{
friend istream&
operator>>(istream& is,SalseItem& si)
{
cout<<"Please input the book name:"<<endl;
getline (cin, si.name);
// ...
欢呼声,
AR
cheers,
AR
这篇关于如何输入“代码项目"之类的字符串?到使用istream的字符串类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文