字符串相关函数

strcmp:C++自带函数---字典序

strcpy:交换顺序

getline:

  • 本质上有两种getline函数,一种在头文件 中,是istream类的成员函数。一种在头文件 中,是普通函数。
    • 中的getline函数有两种重载形式:
      istream& getline (char* s, streamsize n );
      istream& getline (char* s, streamsize n, char delim );
      作用是从istream中读取至多n个字符保存在s对应的数组中。即使还没读够n个字符,如果遇到换行符'\n'(第一 种形式)或delim(第二种形式),则读取终止,'\n'或delim都不会被保存进s对应的数组中。
    • 中的getline函数有四种重载形式:
      istream& getline (istream& is, string& str, char delim);
      istream& getline (istream&& is, string& str, char delim);
      istream& getline (istream& is, string& str);
      istream& getline (istream&& is, string& str);
      用法和上一种类似,不过要读取的istream是作为参数is传进函数的。读取的字符串保存在string类型的str中。
      例
  • getline不是C库函数,而是gcc的扩展定义或者C++库函数。它会生成一个包含一串从输入流读入的字符的字符串,直到以下情况发生会导致生成的此字符串结束。
    • 到文件结束;
    • 遇到函数的定界符;
    • 输入达到最大限度。
  • 比较抽象,那么。。。和cin对比一下
    • 举个例子,比如 cin >> namel;
      然后写一段代码,像这样
    #include <iostream>
    #include <string> 
    using namespace std;
    int main()
    {
      string name;
      string city;    
      cout << "Please enter your name: ";
      cin >> name;
      cout << "Enter the city you live in: ";
      cin >> city;
      cout << "Hello, " << name << endl;
      cout << "You live in " << city << endl;
      return 0;
    }

而结果呢,是这样的
> Please enter your name: John Doe
Enter the city you live in: Hello, John
You live in Doe

所以说虽然可以使用 cin 和 >> 运算符来输入字符串,但它可能会导致一些需要注意的问题:当 cin 读取数据时,它会传递并忽略任何前导白色空格字符(空格、制表符或换行符)。一旦它接触到第一个非空格字符即开始阅读,当它读取到下一个空白字符时,它将停止读取

而在这个示例中,我们根本没有机会输入 city 城市名。因为在第一个输入语句中,当 cin 读取到 John 和 Doe 之间的空格时,它就会停止阅读,只存储John作为name的值。在第二个输入语句中,cin使用键盘缓冲区中找到的剩余字符,并存储 Doe 作为 city 的值。

    • 为了解决这个问题,可以使用一个叫做getline的C++函数。此函数可读取整行,包括前导和嵌入的空格,并将其存储在字符串对象中。
      举个栗子getline(cin, inputLine);
    #include <iostream>
    #include <string> 
    using namespace std;
    int main()
    {
      string name;
      string city;
      cout << "Please enter your name: ";
      getline(cin, name);
      cout << "Enter the city you live in: ";
      getline(cin, city);
      cout << "Hello, " << name << endl;
      cout << "You live in " << city << endl;
      return 0;
    }

输出结果
> Please enter your name: John Doe
Enter the city you live in: Chicago
Hello, John Doe
You live in Chicago

Orz。。。

猜你喜欢

转载自www.cnblogs.com/orange-233/p/12001099.html