用字符串填充字符数组?C++
filling a char array with a string? c++
我需要通过用户提示填充此数组。我想在用户条目中读取一个字符串,然后将该字符串分配给数组,但这似乎不是解决这个问题的正确方法。有人可以帮助我吗?
我收到的错误显示"数组类型 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()
这样的函数来找出实际输入的长度。
您可以使用
strcpy
将string
复制到数组中,也可以使用 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;
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 2D数组来自文本输入,中间有空格
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 使用strcpy将char数组的元素复制到另一个数组
- 使用指针从C++中的数组中获取最大值
- C++使用整数的压缩数组初始化对象
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '