固定:http://pastebin.com/71QxqGk5
第一篇文章/问题。
所以这是C ++,我正在尝试打印一系列单词。
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
#include <cctype>
#include <ctime>
using namespace std;
//structs
struct Input
{
int size;
string* word;
bool is_palindrome[];
};
//prototypes
bool openInputFile(ifstream &ifs);
void File_to_Array(string* word, int &size);
void PrintArray(string* word, int size);
//main
int main()
{
Input myInput = { 0, nullptr, false };
File_to_Array(myInput.word, myInput.size);//copy arr and get size
cout << myInput.word; //this outputs 00000000
cout << *myInput.word; //this breaks and throws exception as commented below
//Exception thrown at 0x0098BB6B in Project1.exe: 0xC0000005: Access violation reading location 0x00000014.
PrintArray(myInput.word, myInput.size);//print array of strings
system("PAUSE");
return 0;
}
//functions
bool openInputFile(ifstream &ifs)
{
string filename;
cout << "Enter the input filename: " << endl;
getline(cin, filename);
ifs.open(filename.c_str());
return ifs.is_open();
}
void File_to_Array(string* word, int &size)//copies file to dyn arr and assigns size from first elem
{
ifstream myFile;
while (!openInputFile(myFile))
cout << "Could not open file" << endl;
string tempstr = "";
getline(myFile, tempstr);//first line is size of dyn arr
size = stoi(tempstr);//now we have max size of dyn arr of strings
word = new string [size];//now we have the array of strings, *word[index] = string1
int i;
for (i = 0; getline(myFile, word[i]) && i < size; ++i);//for each line
//copy line of string from file to string arr within "bool" test, second param of for loop //copying done
size = i;
myFile.close();//done with file, no need, close it
}
void PrintArray(string* word, int size)
{
//for (int i = 0; i < size; ++i)
//cout used to be here, but now its in main, for debugging
}
所以我想知道我的问题是否是传递一个结构的成员,如果我应该将整个结构类型“myInput”传递给函数并使用 - &gt;运算符来访问myInput的成员。
下面的是文本文件的示例
5
month
Runner
NEON
digit
ferret
nothing
5将是动态分配的数组的大小,其余是字符串,因为你可以看到有6个字符串,所以我在for循环中测试文件是否仍在将字符串传输到数组。
答案 0 :(得分:1)
File_to_Array
的这一部分导致问题:
word = new string [size];
您认为您将myInput
对象的指针设置为指向字符串数组,但您并非如此。当您将指针传递给此处的函数时:
File_to_Array(myInput.word, myInput.size)
^^^^^^^^^^^^
你真的传递了一个指针的副本。因此,在File_to_Array
内,此副本重新指向新创建的字符串数组,但myInput
内的实际指针不会更改。您应该传递对指针的引用:
void File_to_Array(string*& word, int &size)
\___________/
^--reference to a pointer
我还建议你改用vector[string]
。最后,您的bool is_palindrome[];
成员及其初始化看起来很奇怪,但由于它们从未在代码中使用过,因此很难进一步评论。