我正在尝试制作一个程序,让人们在他们的偏好文件中输入他们想要在那一周做的事情。我做了一个巨大的if else声明,需要帮助我的else语句。我的其他声明对用户/成员公平,因为他们的列表是随机选择的,并且文件已创建。但是,else语句会创建该文件,但不会将任何角色写入其中。这是代码:
else {
string positions[23] =
{ "Day_Clean" "Dinner_Cook" "Dinner_Cook" "Dinner_Clean" "Dinner_Clean" "HEB_Shop" "Costco_Shop" "Silver_Fridge" "Stove_Micowave" "Appliance_Clean" "LH_Bathrooms" "Laundry_Room" "Upstairs_Commons" "Bikeroom_Entrance_Stairs" "Little_House_Commons" "Porch_Grounds" "Recycling" "Gardening" "Condi_Fridge_Personal_Fridge" "Freezer" "Downstairs_Bathroom_1" "Downstairs_Bathroom_2" "Upstairs_Bathroom" "Big_House_Hallways" };
ofstream randomPrefs;
randomPrefs.open(foo);
int randomPrefloopcount;
do {
int randomPrefs1 = rand() % 25;
randomPrefs << positions[randomPrefs1] << "\n";
randomPrefloopcount++;
} while(randomPrefloopcount <= 24);
randomPrefs.close();
创建了文件,但它们都是空白的。请帮忙!
答案 0 :(得分:0)
验证概念的简单程序:
#include <iostream>
int main()
{
static const char *tokens[] = {"Tory" "Grant"};
static const char *mythbusters[] = {"Adam", "Jamie"};
// Print out the quantity of elements:
std::cout << "Elements in tokens: " << (sizeof(tokens) / sizeof(tokens[0])) << "\n";
std::cout << "Elements in mythbusters: "
<< (sizeof(mythbusters) / sizeof(mythbusters[0]))
<< "\n";
return 0;
}
这将显示字符串文字的连接和指定多个文字之间的区别。
修改:已添加&#39; *&#39;在代币和神话中之前。
答案 1 :(得分:0)
正如Sam Varshavchik所说,你的问题在于数组中元素的数量和循环。
让我们假设你的值永远不会改变,有一种更安全的方式在c ++ 11中声明和使用这样的数组。
#include <array>
#include <iostream>
int main()
{
constexpr std::size_t kArraySize{ 3 };
constexpr std::array<const char *, kArraySize> kArray {
"hehe"
, "hehe"
// , "hehe" // this one would work since there is 3 elements defined
// , "hehe" // this one would fail to compile
};
for (auto element : kArray)
{
if (element != nullptr)
{ std::cout << "element: " << element << std::endl; }
else
{ std::cout << "element is null" << std::endl; }
}
}
std :: array确保用户未定义的值将被初始化为零,在这种情况下,它意味着它们将被归零。
在C ++11§8.5/ 8中指定:
对T类型的对象进行值初始化意味着:
- 如果T是没有用户提供的(可能是cv限定的)类类型 或删除默认构造函数,然后该对象被零初始化..., 如果T有一个非平凡的默认构造函数,那么对象就是 缺省初始化;
引用此post被盗。
编辑,应用于您的代码,它将如下所示:
else {
constexpr std::size_t kArraySize{ 23 };
constexpr std::array<const char *, kArraySize> kPositions { "Day_Clean", "Dinner_Cook", "Dinner_Cook", "Dinner_Clean", "Dinner_Clean", "HEB_Shop", "Costco_Shop", "Silver_Fridge", "Stove_Micowave", "Appliance_Clean", "LH_Bathrooms", "Laundry_Room", "Upstairs_Commons", "Bikeroom_Entrance_Stairs", "Little_House_Commons", "Porch_Grounds", "Recycling", "Gardening", "Condi_Fridge_Personal_Fridge", "Freezer", "Downstairs_Bathroom_1", "Downstairs_Bathroom_2", "Upstairs_Bathroom", "Big_House_Hallways" };
ofstream randomPrefs;
randomPrefs.open(foo);
std::size_t maxRandomLoop { 25 };
for (std::size_t i = 0 ; i < maxRandomLoop ; ++i)
{
int randomPrefs1 = rand() % kArraySize;
if (kPositions[randomPrefs1] != nullptr)
{ randomPrefs << kPositions[randomPrefs1] << "\n"; }
}
randomPrefs.close();
}
重新编辑,你忘记了数组中的逗号。