我在更改字符串数组的值时遇到问题。 代码的要点是检查它的故事编号,然后更改字符串数组的值,然后通过forloop将它打印在choices函数中。
void CheckDecisions(std::string choices[], int num_choices, int story_number)
{
//choices = new std::string[];
const int num = 4;
num_choices = num;
if (story_number == 0)
{
std::string start_choices[num] = { "", "Home", "The Store", "Your friend Taylor's place" };
choices = start_choices;
}
if (story_number == 1)
{
//std::string_choices[num_choices] = { "", "Hummana", "Hummana", "Yes!" };
}
}
它不会更改字符串的值并仍然返回空。什么是正确的语法?
以下是整个代码:
#include <iostream>
#include <string>
#include <vector>
void CheckStoryArk(int choice, std::string story, int story_number)
{
if (story_number == 0)
{
if (story == "Home")
{
printf("story is Home\n");
}
if (story == "The Store")
{
printf("Story is Store\n");
}
if (story == "Your friend Taylor's place")
{
printf("Story is Taylor\n");
}
}
if (story_number == 1)
{
if (story == "whatever")
{
printf("something");
}
}
if (story_number == 2)
{
printf("story number is 3\n");
}
if (story_number == 3)
{
printf("story number is the end\n");
}
}
void CheckDecisions(std::string choices[], int num_choices, int story_number)
{
//choices = new std::string[];
const int num = 4;
num_choices = num;
if (story_number == 0)
{
std::string start_choices[num] = { "", "Home", "The Store", "Your friend Taylor's place" };
choices = start_choices;
}
if (story_number == 1)
{
//std::string_choices[num_choices] = { "", "Hummana", "Hummana", "Yes!" };
}
}
//Prints out choices
void Choices(int num_choices, std::string choices[], int choice, std::string story, int story_number)
{
CheckDecisions(choices, num_choices, story_number);
for (int i = 1; i < num_choices; i++)
{
//printf("%d %s\n", i, choices[i]);
std::cout << i << " " << choices[i] << "\n";
}
std::cin >> choice;
if(choice >= num_choices)
{
printf("That's not a valid answer, dickbag!\n");
std::cin >> choice;
}
story = choices[choice];
CheckStoryArk(choice, story, story_number);
}
void Story(int story_number, const int num_choices, std::string choices[], int choice)
{
printf("You're driving down the streets of Los Angeles, where are you going?\n");
for (int i = 0; i < story_number; i++)
{
Choices(num_choices, choices, choice, choices[choice], i);
}
}
void main()
{
const int num_choices = 4;
int story_number = 4;
int choice = 0;
std::string choices[num_choices] = {};
Story(story_number, num_choices, choices, choice);
}
答案 0 :(得分:0)
这不是你的语法问题,而是你正在调用未定义的行为。
std::string start_choices[num] = { "", "Home", "The Store", "Your friend Taylor's place" };
choices = start_choices;
当您的函数存在时,start_choices
数组将被销毁,因此将其分配给choices
并尝试使用该函数访问它是未定义的。
而是将数据复制到choices
数组中:
std::copy (std::begin(start_choices), std::end(start_choices), choices);
或者只是使用std::vector
并完全避免头痛。