【问题标题】:Inputting one line at a time into a string array in c++一次将一行输入到c ++中的字符串数组中
【发布时间】:2015-12-02 01:06:01
【问题描述】:

这里是编程和 Stackoverflow 的新手。刚刚有一个关于编写类刽子手程序的一部分的问题。

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

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,仅用于上下文。

谢谢!

【问题讨论】:

  • 你应该看看 std::vector (一个可增长的数组)

标签: c++ arrays string file


【解决方案1】:

动态内存分配

假设我们的数组是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
您已输入:75、436、1067、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()<< " ";

输出:

我是一个堆栈

【讨论】:

  • 非常感谢您汇总选项。对于像这样的简单程序,您会推荐 Emile 建议的 linecount grab 吗?编辑:对不起,没有意识到输入实际上输入了评论。我承认我必须查看 cplusplus.com 以了解是否可以了解动态内存和其他选项。 (抱歉,编程第一年)
  • @gameindians 当然他的解决方案很好,但是使用该解决方案,您仍然需要在程序运行之前定义数组大小,我想您会问这个
【解决方案2】:

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

ifstream file("hangman.txt");
string line;
int lineCount = 0;

while (getline(file, line))
    lineCount++;

file.close();

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

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

【讨论】:

  • 试过了,看起来很有效!空行更正语句会像: int emptyline = 0;如果行 = "";空行++;在循环内和最后:linecount=linecount-emptyline;
  • 这可行,但更简单的方法是将原始 lineCount++ 简单地放在 if 中。示例:ifstream file("hangman.txt"); string line; int lineCount = 0; while (getline(file, line)) if (line.length &gt; 0) lineCount++; file.close();
猜你喜欢
  • 2016-04-30
  • 2012-08-27
  • 1970-01-01
  • 2017-05-21
  • 2015-05-23
  • 2023-03-11
  • 2017-03-24
  • 1970-01-01
相关资源
最近更新 更多