Input a string into char

Mar 8, 2021 at 9:46pm
Hello! I have an assignment requiring me to read from a .csv file into a struct array, sort the array by various methods, and display the information. One of the columns of the CSV is the price range, and in it are dollar sign amounts ($, $$, $$$, $$$$). My professor says that I can have those input as char and later when I need to sort by the amount of dollar signs the program will know which struct variables have more and less dollar signs. He also recommended using getline for the .csv file. My problem is that getline returns as a string, and I'm not sure if there's a way for me to swap that to char or if I absolutely have to input it as a char array. Here's the code snippet:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int readRestaurants(ifstream& indata, Restaurant list[], int listSize){
    int index;

    for(index=0; index<listSize || !indata.eof(); index++){
        string rating,
        priceRange,
        reviewNum;
        getline(indata, list[index].name, ',');
        getline(indata, rating, ',');
        list[index].rating = stod(rating);
        getline(indata, priceRange, ',');

        getline(indata, reviewNum, ',');
        list[index].reviewNum = stoi(reviewNum);
    }
return index;
}


And here's the .csv column:
1
2
3
4
5
6
7
8
9
10
11
Price Range
$$$$
$$
$$$
$$
$
$$$$
$$ 
$
$$$$
$
Mar 8, 2021 at 10:32pm
Hello malibuwiley,


My professor says that I can have those input as char and later when I need to sort by the amount of dollar signs the program will know which struct variables have more and less dollar signs.


Please tell me what he is smoking. I think I could use some of it.

First you can not put "$$$$" into a single character. It would have to be a "char*" or a C style array. But this will do nothing any better than "std::string.size()" can do. And the ".length()" function will return the same number as the ".size()" function.

Disregard What followed. My apologies I was looking at the wrong code.

Once I get the code to compile and run I will know more.

Andy

Edit:
Last edited on Mar 8, 2021 at 10:56pm
Mar 9, 2021 at 12:40am
@malibuwiley,
To convert a string to a c-string, use this function:
1
2
3
4
5
6
strcpy (cstring, object.c_str ());
// Where "cstring" is any standard c-string, and
// "object" is a standard string object
// You will need to #include 
// <cstring> for strcpy function, and 
// <string> for c_str function 


Or you can use strncpy() which avoids memory issues by only copying a specified amount of chars from a string.

strcpy:
https://www.cplusplus.com/reference/cstring/strcpy/?kw=strcpy

strncpy:
https://www.cplusplus.com/reference/cstring/strncpy/?kw=strncpy

c_str:
https://www.cplusplus.com/reference/string/string/c_str/

Good luck,
max
Mar 9, 2021 at 11:26am
Topic archived. No new replies allowed.