【发布时间】:2020-07-08 22:00:16
【问题描述】:
当我尝试动态分配数组时,我收到来自以下代码的错误(在我尝试使用 bool 函数递增用户数组中的每个字母之后看到)。这是错误:
main.cpp:在函数‘Word* splitSentene(std::string, int&)’中: main.cpp:81:32:错误:无法在赋值中将“std::string* {aka std::basic_string*}”转换为“Word*” 词=新字符串[i];我正在尝试计算用户输入的单词数量,并为字符串动态分配一个数组。到目前为止,这是我的代码:
#include <iostream>
#include <cctype>
#include <string>
using namespace std;
struct Word
{
string english; // English sentence
string piglatin; // Pig latin sentence
};
// PT 1. Function prototype
Word * splitSentence(const string words, int &size){};
int main()
{
string userSentence;
int size;
// Get the users sentence to convert to pig latin
cout << "Please enter a string to convert to pig latin:\n";
getline(cin, userSentence);
// Directs to Word * splitSentence function
Word* tempptr = splitSentence(userSentence, size);
delete [] tempptr;
return 0;
}
//PT 1. Analyze the sentence
Word * splitSentene(const string words, int &size)
{
bool flag = true;
int num = 0;
for (int i = 0; i < words.length() + 1; i++)
{
//test for white space, then when you hit the first alphabetical character after a space,
//increment up the size of the array
if (isspace(words[i]))
flag = true;
if (isalpha(words[i]));
{
if (flag == true)
{
flag = false;
cout << words[i++];
}
}
// Dynamically allocate the array for the words
Word *sentence = nullptr;
sentence = new string[i];
}
}
这里是 pt 1 的说明,用于进一步说明:
PT。 1) 编写一个函数,将一个英文句子作为一个字符串。这个函数应该首先计算句子中有多少“单词”(单词是由空格分隔的子字符串)。然后它应该分配一个大小等于字数的动态数组。该数组包含 Word 结构(即 Word 类型的数组)。然后该函数将该句子的每个单词存储到相应结构的英语字段中。然后,该函数应使用 return 语句将此数组以及使用引用参数的数组大小返回给调用函数。
此函数还应删除除字母之外的所有大写字母和特殊字符。使用以下原型实现函数:
Word * splitSentence(const string words, int &size);
这是我在这里的第一篇文章,因此我将感谢有关如何动态分配数组和格式化它的任何输入(如果我已经成功编码了如何计算用户输入的句子中的单词)。如果需要提供更多信息,请告诉我!
【问题讨论】:
-
您正在尝试将
std::string*分配给Word*。如果你这样做sentence = new Word[i]会发生什么? -
指令并没有说你必须进行动态内存分配。如果可以,请避免使用
new和delete。 -
Word * splitSentence(const string words, int &size){};-- 我不知道你是否意识到这一点,但 C++ 允许你按值返回:Word splitSentence(const string words, int &size);-- 然后只返回Word对象。不需要动态内存分配。 -
@cigen "指令并没有说你必须进行动态内存分配" - 是的,它确实:“它应该然后分配一个大小等于字数的动态数组。”并且由于该函数返回一个原始的
Word*指针,因此基本上只剩下new[]或malloc()用于该分配。当然,您是对的,应该尽可能避免使用new。可以改用static或thread_localvector<Word>并返回其data(),只要调用者知道返回的指针不指向delete[]。 -
@RemyLebeau 哦,确实如此。我的眼睛一定在上面呆滞了:p
标签: c++