/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
如下代码产生一个console输入循环,接收输入与“password”做比较,一致则跳出循环,不一致则继续接收输入至一致为止。亮点是cin>>getpass>>pw;这句中间加了个方法用以每次在接收输入之前输

出提示消息。注:cin的结束是以回车才能继续下一行代码,如果cin>>a>>b;则识别a,b分开的可以是空格也可以是回车。也即:如果cin>>str;如果输入‘a空格asdf’,则str只是赋值为a而已。
#include <iostream>
#include <cstring>
using namespace std;
istream &getpass(istream &stream)
{   
  cout << '\a';                 // sound bell
  cout << "Enter password: ";

  return stream;
}

int main()
{
  char pw[80];

  do {
    cin >> getpass >> pw;
  } while (strcmp(pw, "password"));

  cout << "Logon complete\n";

  return 0;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
getline的用法
<一>cin.getline()
 char name[80] = {'J', 'e', 'f', 'f', '/0' };
 cout << "Enter your name: ";
 cin.getline(name, 80);
 cout << "Your name is " << name;
可做到一直接收输入并复制给name变量,默认的结束符号为回车,如果变为cin.getline(name,80,'!');则结束接收流的符号变为'!',如果这时输入中带有回车,则会一并收入name中,并能显示回车

换行在屏幕上作为输出name的一部分。
<二>getline( cin, rest, '!');
 string word, rest;
 cout << header << "Press <return> to go on" << endl;
 cin.get();                  // Read the new line without saving.
 cout << "\nEnter a sentence! End with <!> and <return>." << endl;
 cin >> word;                // Read the first word
 getline( cin, rest, '!');   // read a line up to the character !
 cout << "The first word:   " << word  << endl
      << "Remaining text: " << rest << endl;
getline( cin, rest, '!');这条语句讲输入流的都赋值给rest变量,识别结束符为‘!’,这个可以自己设置结束符的,若不设置为回车,则可以正常接收回车并显示。

 

posted on 2006-07-17 11:57 活着就是折腾,所以当然要骠悍的折腾 阅读(7558) 评论(2)  编辑 收藏 引用 所属分类: C++基础
Comments
  • # re: cin和getline的用法
    cj
    Posted @ 2007-11-23 17:47
    为什么我编辑后老是出现st.cpp
    D:\vc\st\st.cpp(15) : error C2679: binary '>>' : no operator defined which takes a right-hand operand of type 'class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >' (or there is no acceptable conversion)
    D:\vc\st\st.cpp(16) : error C2065: 'getline' : undeclared identifier
    D:\vc\st\st.cpp(17) : error C2679: binary '<<' : no operator defined which takes a right-hand operand of type 'class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >' (or there is no acceptable conversion)
    D:\vc\st\st.cpp(18) : error C2146: syntax error : missing ';' before identifier 'cout'
    D:\vc\st\st.cpp(18) : error C2679: binary '<<' : no operator defined which takes a right-hand operand of type 'class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >' (or there is no acceptable conversion)
    执行 cl.exe 时出错.
    这样的错呢  回复  更多评论   
  • # re: cin和getline的用法[未登录]
    ~~~
    Posted @ 2009-08-07 09:33
    谢了~~  回复  更多评论   

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理