在c++中一次向字符串数组中输入一行

Inputting one line at a time into a string array in c++

本文关键字:数组 输入 一行 字符串 c++ 一次      更新时间:2023-10-16

这里是编程和堆栈溢出的新手。刚刚有一个关于编写一个类hangman程序的一部分的问题。

为了尽早开始,我必须手动硬编码答案,并将其设置为随机选择一个,如下所示:

srand(time(NULL));
string Phrases[3] = {"evan almighty","the hunger games","click"};
string SecretWord = Phrases[rand()%3];

我正在尝试使用txt文件作为一种更简单的方式来修改答案列表,而不是弄乱我的主要代码(正如我的教授所建议的那样)。

因此,有人建议我使用getline和一个循环:

string Phrases[10];
ifstream fin("hangman.txt");
for (int x=0; x<10; x++)
{
    getline (fin, Phrases[x]);
}
string SecretWord = Phrases[rand()%10]

它运行良好,但我想知道是否有任何方法可以避免对答案/短语的总数进行硬编码。

这一切都是在CodeBlocks中完成的,使用int main(),并返回0,仅用于上下文。

谢谢!

动态内存分配

假设我们的数组是int array[3]
您说您希望操作系统的内存大小为3*sizeof(int)。您在运行时之前确定阵列的大小
在本例中,您可以在编译时确定数组大小:

#include <iostream>
#include <new>
using namespace std;
int main ()
{
  int i,n;
  int * p;
  cout << "How many numbers would you like to type? ";
  cin >> i;
  p= new (nothrow) int[i];
  if (p == nullptr)
    cout << "Error: memory could not be allocated";
  else
  {
    for (n=0; n<i; n++)
    {
      cout << "Enter number: ";
      cin >> p[n];
    }
    cout << "You have entered: ";
    for (n=0; n<i; n++)
      cout << p[n] << ", ";
    delete[] p;
  }
  return 0;
}

输出:

你想键入多少数字?5
输入数字:75
输入编号:436
输入编号:1067
输入数字:8
输入数字:32
您已输入:754361067,8,32,

此示例取自:http://www.cplusplus.com/doc/tutorial/dynamic/

或者可以使用std::liststd::stackstd::vector等数据类型。。。

堆栈示例:

stack<string> slist;
slist.add("stack");
slist.add("a");
slist.add("am");
slist.add("i");
for(i=0;stack.size();i++)
cout << stack.pop()<< " ";

输出:

我是一个堆叠

一个简单的方法是计算文本文件中的行数。这可以像这样实现:

ifstream file("hangman.txt");
string line;
int lineCount = 0;
while (getline(file, line))
    lineCount++;
file.close();

在这段代码之后,lineCount将包含文本文件中的行数,这应该是答案的数量。

当然,如果文件中有空行,则可能需要在循环中添加if语句,以便在递增计数器之前检查该行是否真的有答案。