Was wodering if someone could help me with why I'm getting a segmentation error?
My goal is to get a string array through stdin, have the input stop on the word "quit" convert the numbers I took in to a float then use them for various purposes. I'm almost posistive my issue lies in how I am converting from string to float. My compiler doesn't want stof so I am force onto atof. Any help is appreciated thanks!!
int main() {
// Set up array a with index i, limit, and num to read in.
int i = 0, limit=1;
string num;
string *a = (string *)malloc(limit*sizeof(int));
float *b = (float *)malloc(limit*sizeof(int));
// Read in nums wh ile able. If 0 entered, exit loop. Put num into
// array. If limit exceeded, double the capacity of the array.
std::cout << "> ";
while (std::cin >> num) {
if (num == "quit") break;
a[i++] = num;
if (i>=limit) {
limit *= 2;
a = (string *)realloc(a, limit*sizeof(int));
}
if (a[i] != NULL){
b[i] = atof(a[i].c_str());
i++;
}
// Print out array
for (int j=0; j<i; j++)
std::cout << a[j] << " ";
std::cout << std::endl;
}
Would help if you tell us what errors so we don't have to guess.
About this statement though - a[i] != NULL this doesnt compile for me. "a" (pick better names for your variables) is a dynamically allocated array of string. I dont think you can compare a string to NULL.
int main() {
32
33 // Set up array a with index i, limit, and num to read in.
34 int i = 0, limit=1;
35 string num;
36 string *a = (string *)malloc(limit*sizeof(int));
37 float *b = (float *)malloc(limit*sizeof(int));
38 // Read in nums wh ile able. If 0 entered, exit loop. Put num into
39 // array. If limit exceeded, double the capacity of the array.
40 std::cout << "> ";
41 while (std::cin >> num) {
42 if (num == "quit") break;
43 a[i++] = num;
44 b[i] = atof(a[i].c_str());
45 if (i>=limit) {
46 limit *= 2;
47 a = (string *)realloc(a, limit*sizeof(int));
48 b = (float *)realloc(b, limit*sizeof(int));
49 }
50 }
51
52
53 // Print out array
54 for (int j=0; j<i; j++)
55 std::cout << a[j] << " ";
56 std::cout << std::endl;
57 }
You may not use malloc with non-trivial C++ types (such as std::string) without bad things happening. (Unless you're versed in the nuances of placement new, which you clearly are not.)
malloc only allocates memory. No object is constructed in that memory, so treating it as an array of constructed objects is a mistake.