zoukankan      html  css  js  c++  java
  • cin.get(), cin.getline() 用法

    cin.getline( name, LEN )可以读取一行字符串,通过换行符确定已经读到行尾,但它不保存换行符。

    cin.get( name, LEN )可以读取一行字符串,但会将换行符留在输入队列当中,后面程序出现cin读取输入时,cin会先读到换行符从而忽略过去。

    所以,可以写成这样:

    cin.get(name, LEN);  // Read first line.

    cin.get(); // Read new line.

    cin.get(name2, LEN);  //Read second line.

    cin.get()返回一个cin对象,所以可以这么去用,下面两种语句相同:

    cin.get(name, LEN).get();  

    cin.getline(name1, LEN).getline(name2, LEN);

    numstr.cpp

      cout << "What year was your house built? \n";

      int year ;

      cin >> year;

      cout << "What is its street address?\n";

      char address[80];

      cin.getline(adress, 80);

      cout << "year built: " << year << endl; 

      cout << "Address :" << address << endl;

      cout<< "Done!"<< "\n";

      return 0; 

    用户输入year后,会将换行留在输入队列,导致输入address的时候,cin先读到换行,直接导致输入结束。

    解决方案可以用 cin.get 加入到 cin >> year;之后。

    或者 (cin >> year) . get();

  • 相关阅读:
    Altium Designer如何从已有的PCB图中导出封装库
    获得内核函数地址的四种方法
    poj2976 Dropping tests
    poj3045 Cow Acrobats
    CF916C Jamie and Interesting Graph
    poj3104 Drying
    poj2455 Secret Milking Machine
    poj2289 Jamie's Contact Groups
    网络流最小路径覆盖
    CF897C Nephren gives a riddle
  • 原文地址:https://www.cnblogs.com/TadGuo/p/7538988.html
Copyright © 2011-2022 走看看