首页 > 解决方案 > 这段代码在 C++ 中的问题是什么?我必须使用 c-string

问题描述

我创建了一个 c 字符串数组。此代码接受三个字符串的输入,然后将其显示在控制台上。但不幸的是,输入很好,但输出显示不起作用。

int main()
{
    char *str[20];
    std::cout << "Enter values to strings: ";
    for (int i = 0; i < 3; i++)
    {
        std::cout << "\nstr" << i<<": ";
        std::cin >> str[i];
    }
    std::cout << "\n\n\nouput:";
    for (int i = 0; i < 3; i++)
    {
        std::cout << "\nstr" << i<<":";
        std::cout << str[i];
    }
    return 0;
}
    

标签: c++c-strings

解决方案


正如评论中提到的,使用未初始化的指针是未定义的行为。如果您需要使用 C 字符串(即您不能使用std::string,我通常会推荐),只需使用 为您的 C 字符串分配内存operator new。一种可能的方法是定义预期输入字符串的一些恒定最大长度,将输入读取到缓冲区,然后分配必要的内存并将数据复制到新分配的空间:

#include <iostream>
#include <cstring>

constexpr int MAX_STR_LEN = 255;

int main()
{
    char *str[20];
    char buff[MAX_STR_LEN];  // going to read strings here and copy them to `str` array
    std::memset(buff, 0, MAX_STR_LEN);  // fill the buffer with zeroes
    std::cout << "Enter values to strings: ";
    for (int i = 0; i < 3; i++)
    {
        std::cout << "\nstr" << i<<": ";
        std::cin >> buff;
        str[i] = new char[std::strlen(buff)+1];  // +1 for terminating null
        std::memcpy(str[i], buff, std::strlen(buff));
        str[i][std::strlen(buff)] = 0;  // last character should be null
    }
    std::cout << "\n\n\nouput:";
    for (int i = 0; i < 3; i++)
    {
        std::cout << "\nstr" << i<<":";
        std::cout << str[i];
        delete[] str[i];
    }
    return 0;
}

请注意,此示例仅用于练习目的,通常 C++ 开发人员会使用std::vector<std::string>来保持字符串的动态数组。


推荐阅读