-5

我是 C++ 的新手,我已经尝试了所有我现在和研究但到目前为止没有运气,这是我应该做的:

  • 在这个作业中,您将允许用户输入一些简短的单行句子。
  • 每个句子都被添加到 500 个字符的缓冲区中。
  • 确保缓冲区中的每个句子都以空值结尾。
  • 将每个句子添加到此缓冲区时,将指向该句子的指针存储在 char 指针数组中。
  • 当用户输入零时,停止从用户获取输入并以相反的顺序显示缓冲区中的句子。
  • 请注意,句子的顺序是相反的,而不是句子中的单词。例如,如果用户键入。

我目前坚持第一部分。

int main () {
  int const SIZE = 500;
  char sentences[SIZE];
  char* pointers[SIZE];

  do {
   cout<<"Please enter small sentences, hit enter to continue or 0 to stop: "<<endl;
   cin.getline(sentences, 30);
   *pointers = sentences;
   cin.ignore();
 } while (!(cin.getline>>0));

 system ("PAUSE");
 return 0;

}

有人可以帮忙吗?

4

3 回答 3

0

您没有将字符附加到数组,也没有将指针附加到指针数组。

以下是您需要执行的一些步骤:
1. 维护指向“sentences”数组中下一个可用位置的索引或指针。
2. 从文件文件中读取字符串后,将其内容复制到“句子”数组中的下一个可用位置。参见 std::string::c_str() 或 std::string::data() 从字符串转换为“char *”。
3. 维护指向指针数组中下一个可用位置的指针或索引。
4. 将句子指针复制到指针数组中的下一个可用位置。
5. 将句子指针前进字符串的长度。
6. 将指针指针前移一位。

未提供代码,因为这会破坏分配的目的。

于 2013-10-03T18:53:53.177 回答
0

这里有一个提示 - 声明基本数据,并且您需要对这些数据进行操作的方法:

class Buffer       //buffer data combined with methods
{
private:
    char* buffdata;     //buffer to hold raw strings
    int buffsize;       //how big is buffdata
    int bufflast;       //point to null terminator for last saved string
    char** ray;         //declare ray[raysize] to hold saved strings
    int raysize;        //how big is ray[]
    int raycount;       //count how many strings saved
//methods here
public:
    Buffer() //constructor
    { // you figure out what goes here...
    }
    ~Buffer() //destructor
    { // release anything stored in buffers
    }
    add(char *str); //define method to add a string to your data above
    get(unsigned int index); //define method to extract numbered string from stored data
};
于 2013-10-03T21:30:38.717 回答
-1

剧透警报

#include <cstring>
#include <iostream>

int main() {
  const int SIZE = 500;
  char sentenceBuffer[SIZE] = {0};
  char* sentences[SIZE / 2] = {0}; // shortest string is a char + '\0'
  int sentenceCount = 0;
  char* nextSentence = &sentenceBuffer[0];

  std::cout << "Enter sentences. Enter 0 to stop.\n";

  while (std::cin.getline(nextSentence, SIZE - (nextSentence - &sentenceBuffer[0]))) {
    if (0 == std::strcmp(nextSentence, "0")) {
      break;
    }
    sentences[sentenceCount] = nextSentence;
    ++sentenceCount;
    nextSentence += std::cin.gcount(); // '\n' stands in for '\0'
  }

  for (int i = sentenceCount - 1; i != -1; --i) {
    std::cout << sentences[i] << "\n";
  }

  return 0;
}
于 2013-10-03T19:06:26.410 回答