1. 程式人生 > >4.std::string中庫函數的使用。

4.std::string中庫函數的使用。

col class 不知道 name pau 空白 ket 不同的 技術分享

為了美觀,我們把輸入和輸出設計成如下:

      技術分享

#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()函數返回字符串的長度,不包含‘\0‘。

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!

4.std::string中庫函數的使用。