跳转到内容

C++ 字符串输入输出

来自代码酷

C++字符串输入输出[编辑 | 编辑源代码]

介绍[编辑 | 编辑源代码]

在C++中,字符串的输入输出是处理文本数据的基本操作。C++提供了多种方式来处理字符串的输入和输出,包括使用标准输入输出流(iostream)和字符串流(sstream)。理解这些操作对于文件处理、用户交互和数据处理至关重要。

C++中的字符串主要有两种表示方式: 1. C风格的字符数组(以空字符'\0'结尾) 2. C++的std::string类(更现代、更安全的处理方式)

本文将重点介绍如何使用std::string类进行输入输出操作。

基本输入输出方法[编辑 | 编辑源代码]

使用iostream进行输入输出[编辑 | 编辑源代码]

最基本的字符串输入输出可以通过cincout实现。

#include <iostream>
#include <string>

int main() {
    std::string name;
    
    // 输出提示
    std::cout << "请输入您的名字: ";
    
    // 输入字符串
    std::cin >> name;
    
    // 输出结果
    std::cout << "您好, " << name << "!" << std::endl;
    
    return 0;
}

输入示例:

请输入您的名字: Alice

输出示例:

您好, Alice!

注意:cin使用空格作为分隔符,因此它只能读取单个单词。要读取包含空格的整行文本,需要使用getline()函数。

使用getline读取整行[编辑 | 编辑源代码]

#include <iostream>
#include <string>

int main() {
    std::string fullName;
    
    std::cout << "请输入您的全名: ";
    std::getline(std::cin, fullName);
    
    std::cout << "您的全名是: " << fullName << std::endl;
    
    return 0;
}

输入示例:

请输入您的全名: Alice Johnson

输出示例:

您的全名是: Alice Johnson

字符串流处理[编辑 | 编辑源代码]

C++提供了<sstream>库,允许将字符串作为流来处理,这在字符串解析和格式化中非常有用。

字符串输入流(istringstream)[编辑 | 编辑源代码]

#include <iostream>
#include <string>
#include <sstream>

int main() {
    std::string data = "42 3.14 Hello";
    std::istringstream iss(data);
    
    int num;
    double pi;
    std::string word;
    
    iss >> num >> pi >> word;
    
    std::cout << "数字: " << num << "\n"
              << "PI值: " << pi << "\n"
              << "单词: " << word << std::endl;
    
    return 0;
}

输出:

数字: 42
PI值: 3.14
单词: Hello

字符串输出流(ostringstream)[编辑 | 编辑源代码]

#include <iostream>
#include <string>
#include <sstream>

int main() {
    std::ostringstream oss;
    
    oss << "年龄: " << 25 << ", 分数: " << 95.5;
    
    std::string result = oss.str();
    std::cout << result << std::endl;
    
    return 0;
}

输出:

年龄: 25, 分数: 95.5

常见问题与解决方案[编辑 | 编辑源代码]

混合使用cin和getline的问题[编辑 | 编辑源代码]

cingetline混合使用时,可能会出现意外行为,因为cin会留下换行符在输入缓冲区中。

问题代码:

int age;
std::string name;

std::cout << "请输入年龄: ";
std::cin >> age;
std::cout << "请输入姓名: ";
std::getline(std::cin, name); // 会直接跳过

解决方案:cin后使用cin.ignore()清除缓冲区。

std::cin >> age;
std::cin.ignore(); // 忽略换行符
std::getline(std::cin, name);

实际应用案例[编辑 | 编辑源代码]

用户注册系统[编辑 | 编辑源代码]

以下是一个简单的用户注册系统示例,展示如何处理字符串输入:

#include <iostream>
#include <string>
#include <vector>

struct User {
    std::string username;
    std::string email;
    int age;
};

int main() {
    std::vector<User> users;
    char choice;
    
    do {
        User newUser;
        
        std::cout << "\n=== 用户注册 ===" << std::endl;
        std::cout << "用户名: ";
        std::getline(std::cin, newUser.username);
        
        std::cout << "邮箱: ";
        std::getline(std::cin, newUser.email);
        
        std::cout << "年龄: ";
        std::cin >> newUser.age;
        std::cin.ignore(); // 清除缓冲区
        
        users.push_back(newUser);
        
        std::cout << "\n添加更多用户? (y/n): ";
        std::cin >> choice;
        std::cin.ignore();
        
    } while (choice == 'y' || choice == 'Y');
    
    // 显示所有用户
    std::cout << "\n=== 注册用户列表 ===" << std::endl;
    for (const auto& user : users) {
        std::cout << "用户名: " << user.username
                  << ", 邮箱: " << user.email
                  << ", 年龄: " << user.age << std::endl;
    }
    
    return 0;
}

示例交互:

=== 用户注册 ===
用户名: JohnDoe
邮箱: john@example.com
年龄: 30

添加更多用户? (y/n): y

=== 用户注册 ===
用户名: Alice Smith
邮箱: alice@example.org
年龄: 25

添加更多用户? (y/n): n

=== 注册用户列表 ===
用户名: JohnDoe, 邮箱: john@example.com, 年龄: 30
用户名: Alice Smith, 邮箱: alice@example.org, 年龄: 25

高级主题[编辑 | 编辑源代码]

格式化输出[编辑 | 编辑源代码]

C++提供了多种方式来格式化字符串输出,包括设置宽度、精度和对齐方式。

#include <iostream>
#include <iomanip>
#include <string>

int main() {
    std::string items[3] = {"Apple", "Banana", "Orange"};
    double prices[3] = {2.5, 1.99, 3.25};
    
    std::cout << std::left << std::setw(15) << "商品"
              << std::right << std::setw(10) << "价格" << std::endl;
    std::cout << std::setfill('-') << std::setw(25) << "" << std::endl;
    std::cout << std::setfill(' ');
    
    for (int i = 0; i < 3; ++i) {
        std::cout << std::left << std::setw(15) << items[i]
                  << std::right << std::setw(10) << std::fixed 
                  << std::setprecision(2) << prices[i] << std::endl;
    }
    
    return 0;
}

输出:

商品              价格
-------------------------
Apple             2.50
Banana            1.99
Orange            3.25

性能考虑[编辑 | 编辑源代码]

对于大量字符串操作,性能可能成为问题。以下是一些优化建议: 1. 预分配字符串空间(使用reserve()方法) 2. 避免不必要的字符串拷贝(使用引用或移动语义) 3. 考虑使用string_view(C++17引入)进行只读访问

总结[编辑 | 编辑源代码]

C++提供了丰富的字符串输入输出功能,从简单的cin/cout到更高级的字符串流处理。理解这些工具的正确使用方法对于开发健壮的C++应用程序至关重要。关键点包括:

  • 使用getline读取包含空格的整行文本
  • 正确处理混合输入情况(cin后使用ignore
  • 利用字符串流进行复杂的字符串解析和构建
  • 考虑性能优化技术以提高效率

掌握这些概念将使你能够有效地处理各种字符串输入输出场景。