-
strcpy
I'm trying to assign a string to a string array, but I keep getting the 'cannot convert parameter' error. Here's the syntax I'm using:
Code:
string data;
string *cargo_name_array;
cargo_name_array = new string[n+1];
strcpy(cargo_name_array[i], data);
-
strcpy copies C-style char arrays, not C++ style std::string objects.
The regular assignment operator is used to assign one string to another.
-
How else can I assign a string to an array?
-
Simple assignment to the array element:
Code:
cargo_name_array[i] = data;
-
So that wasn't the problem. I'm confused because the test lines at the bottom still do not work. The strings are not stored correctly:
Code:
ifstream cargo_in("cargo_input.txt"); //opens input file
//gets number of lines
if (cargo_in.is_open()) {
while (cargo_in.good()) {
getline(cargo_in,data);
n++; //line counter up
};
}
else { //file access verification
cout << "Input file access error.";
return 0;
};
cargo_in.clear();
//declares dynamic arrays for cargo parameters
cargo_name_array = new string[n+1];
cargo_duration_array = new int[n];
cargo_size_array = new int[n];
for (i=1; i<n+1; i++) {
getline(cargo_in, data, '\t'); //gets string until tab
cargo_name_array[i] = data; //stores string in array
while (cargo_in.get() == '\t'); //discards consecutive tabs
cargo_in.unget(); //moves back one character
getline(cargo_in, data, '\t'); //gets size string until tab
//converts string to decimal and stores size value
cargo_size_array[i] = (int) strtod(data.c_str(), NULL);
getline(cargo_in, data); //gets duration string
//converts string to decimal and stores duration value
cargo_duration_array[i] = (int) strtod(data.c_str(), NULL);
}
cargo_in.close(); //closes input file
}
cargo cargo1;
cargo *ptr;
ptr = &cargo1;
ptr->name = cargo_name_array[1];
ptr->size = cargo_size_array[1];
ptr->duration = cargo_duration_array[1];
-
Arrays are always indexed starting at 0 and ending at size - 1. Do not attempt to do otherwise...that way lies madness! Also, using parallel arrays as you are is an ugly solution. You should consider using a class, or at least a struct.
Why not print out the value of cargo_name_array[i] right after you set it, to ensure it's what you think it should be? Barring that, learning how to use the debugger would be useful.