gpt4 book ai didi

c++一次读入一个字符的c风格字符串?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:01:28 25 4
gpt4 key购买 nike

在 C++ 中,id 喜欢一次将一个字符读入 C 风格的字符串中。如果不首先创建具有设定大小的字符数组(您不知道用户将输入多少个字符),您将如何做到这一点。既然你不能调整数组的大小,这是怎么做到的?我一直在思考这些问题,但这行不通。

char words[1];
int count = 0;

char c;
while(cin.get(c))
{
words[count] = c;
char temp[count+1];
count++;
words = temp;
delete[] temp;
}

最佳答案

因为您不能使用 std::vector,我假设您也不能使用 std::string。如果可以使用std::string,则可以使用the answer by @ilia提供的解决方案.

否则,您唯一的选择是:

  1. 使用指向动态分配内存的指针。
  2. 跟踪分配数组的大小。如果要存储的字符数超过当前大小,增加数组大小,分配新内存,将内容从旧内存复制到新内存,删除旧内存,使用新内存。
  3. 删除函数末尾分配的内存。

我的建议是:

#include <iostream>

int main()
{
size_t currentSize = 10;

// Always make space for the terminating null character.
char* words = new char[currentSize+1];
size_t count = 0;

char c;
while(std::cin.get(c))
{
if ( count == currentSize )
{
// Allocate memory to hold more data.
size_t newSize = currentSize*2;
char* temp = new char[newSize+1];

// Copy the contents from the old location to the new location.
for ( size_t i = 0; i < currentSize; ++i )
{
temp[i] = words[i];
}

// Delete the old memory.
delete [] words;

// Use the new memory
words = temp;
currentSize = newSize;
}

words[count] = c;
count++;
}

// Terminate the string with a null character.
words[count] = '\0';

std::cout << words << std::endl;

// Deallocate the memory.
delete [] words;
}

关于c++一次读入一个字符的c风格字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35885046/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com