在c++中一次向字符串数组中输入一行
Inputting one line at a time into a string array in c++
这里是编程和堆栈溢出的新手。刚刚有一个关于编写一个类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::list
、std::stack
、std::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语句,以便在递增计数器之前检查该行是否真的有答案。
相关文章:
- 检查TCHAR数组输入是否为带符号整数C++
- C++数组输入不接受一定数量的整数
- 为什么我的代码无法处理大型数组输入(>10000)?
- 我正在努力处理多维数组输入和输出,我管理输入,但是打印无法按计划工作
- 使用无符号字符数组输入十六进制数
- C++用用户输入在循环中填充 char 数组:输入整个字符串时到底发生了什么?
- 如何从用户获取数组输入
- C 2x2数组输入线
- 字符数组输入限制
- 将字符串数组输入到函数C++
- C++:如何将普通话(字符串)分配给用户使用数组输入的数字 &运算符问题
- 数组排序、数组输入、数组输出
- 将字符数组输入stdin
- 如何在 c++ 中为对象数组输入字符串
- 如何在c++ mex文件中访问多维数组输入
- 读取文件并将其作为整型数组输入
- 从c++文件中获取输入(矩阵数组输入)
- 数组输入不工作
- 函数结构数组输入cin问题
- 结束数组输入(c++行业标准)