Loading

C++常见的输入方式

输入流对象cin成员函数输入单个字符

  • 成员函数get(char&),可以读取、显示并且不跳过空格和可打印字符
  • 成员函数get(void),要读取空白字符,使用返回值来将输入传递给程序

单字符输入函数的特性总结:

特征 cin.get(ch) ch = cin.get()
传输输入字符的方法 赋给参数ch 将函数返回值赋给ch
字符输入时函数的返回值 指向istream对象的引用 字符编码(int值)
达到文件尾时函数的返回值 转换为false EOF

输入流对象cin成员函数输入字符串

  • 成员函数istream &get(char *, int, char),将换行符留在输入流中
  • 成员函数istream &get(char *, int),将换行符留在输入流中
  • 成员函数istream &getline(char *, int, char),抽取并丢弃输入流中的换行符
  • 成员函数istream &getline(char *, int),抽取并丢弃输入流中的换行符

第一个参数是要写入的字符串地址,第二个参数是字符个数,第三个参数(如果有)是分界字符,遇到分界字符后字符串截止。

示例:

// get_fun.cpp -- using get() and getline()
#include <iostream>

const int Limit = 255;
using namespace std;

int main()
{
    char input[Limit];
    cout << "Enter string: " << endl;
    cin.getline(input, Limit, '#');
    cout << "Your input: " << endl;
    cout << input << "Done with phase 1\n";

    char ch;
    cin.get(ch);
    cout << "Next char is " << ch << endl;

    if(ch != '\n')
        cin.ignore(Limit, '\n');    //读取输入流中的Limit个字符并丢弃或遇到第一个换行符'\n'
    
    cout << "Enter new string:\n";
    cin.get(input, Limit, '?');

    cout << "Your input: " << endl;
    cout << input << "Done with phase 2\n";

    cin.get(ch);
    cout << "Next char is " << ch << endl;

    return 0;
}

输出结果,黑色加粗的部分是通过键盘输入

Enter string:
this is a string name my name #is ba
Your input:
this is a string name my name Done with phase 1
Next char is i
Enter new string:
hhh
test my?demo

Your input:
hhh
test myDone with phase 2
Next char is ?

可以看到getline()成员函数会丢弃输入中的分界字符#,所以读取到输入流中的下一个字符是i。而get()成员函数不会丢弃输入中的分界字符?,所以读取到输入流中的下一个字符是?

char line[50];
cin.get(line, 50);	//将换行符留在输入流cin中

使用cin提取符读取字符

使用cin >> ch方式读取一个字符,会自动跳过空白(如换行符、空格、制表符)

char ch1, ch2;
cin >> ch1 >> ch2;
cout << "ch1: " << ch1 << ", ch2: " << ch2;

输出结果:

h j
ch1: h, ch2: j

输入h j,提取符>>会跳过空白字符,所以ch2输出结果是j,而不是[空格]

使用getline()函数

用法:

cout << "Input string: ";
std::string str;
getline(cin, str); 	//从输入流中读取一行数据到str中,默认分界字符是'\n'
cout << "Output string: " << str;	

输出结果如下,可以看到不会跳过空格,遇到换行符时截止

Input string: hello world
Output string: hello world

参考资料

《C++ Primer Plus 第6版》

https://cplusplus.com/

posted @ 2024-08-04 23:14  记录学习的Lyx  阅读(1)  评论(0编辑  收藏  举报