用字符串填充字符数组?C++

filling a char array with a string? c++

本文关键字:C++ 数组 字符 字符串 填充      更新时间:2023-10-16

我需要通过用户提示填充此数组。我想在用户条目中读取一个字符串,然后将该字符串分配给数组,但这似乎不是解决这个问题的正确方法。有人可以帮助我吗?

我收到的错误显示"数组类型 array[100] 不可分配"

    #include <iostream>
    #include <cstdlib>
    #include <ctime>
    #include <string.h>
    using namespace std;
    int main()
    {
        string theString;
        char array[100]; // ARRAY MAX SIZE
        int length = sizeof(array)-1;
        char * ptrHead = array;
        char *ptrTail = array + length - 1;

        //USER PROMPTS & ARRAY FILL
        cout << "Please enter a string to be reverse: " << endl;
        cin >> theString;
        array= theString;
        //WHILE LOOP SWAPPING CHARACTERS OF STRING
        while (ptrHead < ptrTail)
        {
            char temp = *ptrHead;
            *ptrHead = *ptrTail;
            *ptrTail = temp;
            ptrHead++;
            ptrTail--;
        }
        cout << array << endl;
        return 0;
    }

数组不可分配。您应该在此处使用strcpy

但为此,您必须将theString转换为类似 C 的字符串。

strcpy(array,  theString.c_str() );

然后也调整你的ptrTail指针,如下所示:

int length = theString.size();
char *ptrTail = array + length - 1;

See Here

cin >> array;应该将输入直接放入数组中,我猜这就是您想要的

此外,字符串反转逻辑中存在问题。您正在反转整个数组,而不仅仅是已填充的部分,这会将填充的部分放在数组的末尾。考虑使用像strlen()这样的函数来找出实际输入的长度。

您可以使用

strcpystring复制到数组中,也可以使用 cin >> array 将数据直接输入到数组中,但更好的解决方案是不使用char数组,只需使用算法中的string。这也是一个更好的解决方案,因为您可以溢出固定大小char数组

cout << "Please enter a string to be reverse: " << endl;
cin >> theString;
for (unsigned int i = 0; i <= theString.size() / 2; ++i)
    swap(theString[i], theString[theString.size() - 1 - i);
cout << theString<< endl;

编辑

使用指针相同:

std::cout << "Please enter a string to be reverse: " << std::endl;
std::cin >> theString;
char* i = &theString[0];
char* j = &theString[theString.size() - 1];
for (; i < j; ++i, --j)
    std::swap(*i, *j);
std::cout << theString << std::endl;