4.std::string中库函数的使用。

为了美观,我们把输入和输出设计成如下:

      

#include <iostream>
#include <string>

int main()
{
    
    std::string name;
    std::string s3,s2;
    std::cout << "Please enter your first name: ";
    std::cin >> name;
    s3 =  "* Hello, " + name + "! *" ;
    std::string s1(s3.size(), '*');
    std::string spaces(s3.size() - 2, ' ');
    s2 = "*" + spaces + "*";
    std::cout << s1 << std::endl;
    std::cout << s2 << std::endl;
    std::cout << s3 << std::endl;
    std::cout << s2 << std::endl;
    std::cout << s1 << std::endl;
    system("pause");
    return 0;
}

这里运用到的方法:

1.string的构造函数 string(int size, char ch)。指定字符串的长度,字符串中所有字符设置为ch。

2.string::size()函数返回字符串的长度,不包含''。

3.string类中重载了 + 号。 直接 "something" + string 返回string类型。

课后习题:

1)下面的声明有效吗?

const std::string hello = "Hello";
const std::string message = hello + ", world" + "!";

有效。

2)下面的程序正确吗?

#include <iostream>
#include <string>

int main()
{
    { const std::string s = "a string";
      std::cout << s << std::endl; }
   
    { const std::string s = "another string";
      std::cout << s << std::endl; }
    return 0;
}

正确。 {}里面声明的变量,范围就是声明它的{}。所以可以在两个不同的{}{}中声明名称一样的变量。

3)下面的程序输出正确吗?

#include <iostream>
#include <string>

int main()
{
    { const std::string s = "a string";
      std::cout << s << std::endl;
    { const std::string s = "another string";
      std::cout << s << std::endl; }}
    return 0;
}

正确。输出和上一个程序一样。不同的是。在第二个{}里面。声明的s变量,覆盖了外部声明的s变量。

把倒数第三行的}}改成};}程序输出正确吗?

#include <iostream>
#include <string>

int main()
{
    
    { const std::string s = "a string";
      std::cout << s << std::endl;
    { const std::string s = "another string";
      std::cout << s << std::endl; };}     

    system("pause");
    return 0;
}

正确。和上一个例子不同的在于,第一个{}里面多了一个;的空白语句。

4)下面的程序正确吗?

#include <iostream>
#include <string>

int main()
{
    { std::string s = "a string";
    { std::string x = s + ", really";
    std::cout << s << std::endl; }
    std::cout << x << std::endl;
    }
    return 0;
}

不正确。x声明在第二个{}范围了。出了第二个{}范围,就不知道x是什么了。

修改如下,把x的声明放在第一个{}里面

int main()
{
    
    { std::string s = "a string";
        std::string x;
    {  x = s + ", really";
    std::cout << s << std::endl; }
    std::cout << x << std::endl;
    }
    
   

    system("pause");
    return 0;
}

5)下面程序输入 Samuel Beckett 预测输出?

#include <iostream>
#include <string>

int main()
{
    
    std::cout << "What is your name? ";
    std::string name;
    std::cin >> name;
    std::cout << "Hello, " << name
              << std::endl << "And what is yours? ";
    std::cin >> name;
    std::cout << "Hello, " << name
              << "; nice to meet you too!" << std::endl;
   
   

    system("pause");
    return 0;
}

输入Samuel Beckett
输出:
What is your name? Samuel Beckett
Hello, Samuel
And what is yours? Hello, Beckett; nice to meet you too!

原文地址:https://www.cnblogs.com/billxyd/p/7022233.html