C++ question

Discussion in 'Tech Discussion' started by Zaart, Feb 26, 2020.

  1. Zaart

    Zaart Deer Master Race

    Joined:
    Oct 15, 2016
    Messages:
    1,320
    Likes Received:
    2,011
    Reading List:
    Link
    Hi guys,
    so i'm kinda new to c++ and with this code which is supposed to cut a string into an array
    Code:
    std::vector<std::string> str_to_tab(std::string str)
    {
        int n = 0;
        int g = 0;
        int b = 0;
    
        for (int i = 0; str[i] != '\0'; i++) {
            if (str[i] == ' ')
                n++;
        }
        std::vector<std::string> sorted(n + 1);
        n = 0;
        for (int i = 0; str[i] != '\0'; i++) {
            if (str[i] != ' ') {
                g = 1;
                sorted[n][b] = str[i];
                sorted[n][b + 1] = '\0';
                b++;
            } else {
                if (g != 0) {
                    n++;
                }
                g = 0;
                b = 0;
            }
        }
        std::cout << sorted[1] << " :: " << str << std::endl;
        return (sorted);
    }
    
    int main(int ac, char **av)
    {
        std::vector<std::string> taf = str_to_tab("yop yap yip");
        std::cout << taf[0];
    }
    i was supposed to see the array cut at the space
    but my code display nothing as if the first case of the array was '\0'
    when i print the case one by one i get my letters and with an if i checked and i'm supposed to have a '\0' at the end
    can someone illuminate this poor soul?
     
  2. animestar411

    animestar411 Well-Known Member

    Joined:
    Apr 28, 2016
    Messages:
    533
    Likes Received:
    822
    Reading List:
    Link
    Trying slader or chegg. God, I hated C++ only managed to pass that class cause people virtually failed the final and the curve was high
     
    Zaart likes this.
  3. zajrus

    zajrus Well-Known Member

    Joined:
    May 30, 2019
    Messages:
    186
    Likes Received:
    152
    Reading List:
    Link
    Dunno about C++, but I think I found the problem... there is nothing in the code that would indicate that the str contains a '\0'... so first try to add a '\0' to the end of the str if you want this solution to work...
     
  4. DocB

    DocB "I see you, little mouse! Run along"

    Joined:
    Nov 10, 2015
    Messages:
    3,573
    Likes Received:
    8,110
    Reading List:
    Link
    do what any c debugger does, put cout in the middle of the function for all used variables to see what is actually working on,
    cause it can really be anything, since bad defined constants/strings, sorting that puts the end condition as the first term, mismatched or repeting variables, missing paraenthesis, commas etc
     
    Last edited: Feb 26, 2020
  5. lunarshadow

    lunarshadow Well-Known Member

    Joined:
    Oct 11, 2016
    Messages:
    1,443
    Likes Received:
    1,760
    Reading List:
    Link
    I'd change the 2nd condition of your for loops from
    str != '\0'
    to
    i < str.length()
     
  6. lnv

    lnv ✪ Well-Known Hypocrite

    Joined:
    Jan 24, 2017
    Messages:
    7,702
    Likes Received:
    9,044
    Reading List:
    Link
    It's been a long time and I only did C, but why are you treating your string like an array? isn't it something like str.at(i) ?

    Also, why not use length?
     
  7. Zaart

    Zaart Deer Master Race

    Joined:
    Oct 15, 2016
    Messages:
    1,320
    Likes Received:
    2,011
    Reading List:
    Link
    str is a hard coded string so the '\0' is added without my help

    already done:
    sorted[0][0] is 'y'
    sorted[0][1] is 'o'
    sorted[0][2] is 'p'
    and i even tried adding just before the display sorted[0][3] = '\0'

    thanks but it doesn't change anything ^^
    hum good question i also mostly used c before and i though a string was kinda like a class for char *
     
  8. coyotte508

    coyotte508 Active Member

    Joined:
    Nov 16, 2015
    Messages:
    19
    Likes Received:
    6
    Reading List:
    Link
    Last edited: Feb 26, 2020
    Zaart likes this.
  9. persondb

    persondb Active Member

    Joined:
    Feb 26, 2020
    Messages:
    1
    Likes Received:
    1
    Reading List:
    Link
    You should stop bothering with this C-style code since this is, what I assume for, a C++ course.
    Use the class function find to get the first occurrence of the space in the string and you can copy it using the string constructor
    string (const string& str, size_t pos, size_t len = npos)
    You do the rest iteratively or you can do a pretty recursive function. But finding spaces and cutting the substring is literally just that.

    By god, it has been a couple of years since I last touched C++.
     
    Zaart likes this.
  10. DocB

    DocB "I see you, little mouse! Run along"

    Joined:
    Nov 10, 2015
    Messages:
    3,573
    Likes Received:
    8,110
    Reading List:
    Link
    so basically if you try cout sorted [x][y] it give the correct value but you try to print sorted [x] it does not print all the collumns of that line?
    if it is this, it is becuase cout is not made to print arrays, so you will have to define a function to print arrays
     
    Zaart likes this.
  11. Zaart

    Zaart Deer Master Race

    Joined:
    Oct 15, 2016
    Messages:
    1,320
    Likes Received:
    2,011
    Reading List:
    Link
    .....
    thanks a lot guys!!!!!!!
    i might have spent 3h working on this Q-Q and hitting stuff with a club
     
  12. coyotte508

    coyotte508 Active Member

    Joined:
    Nov 16, 2015
    Messages:
    19
    Likes Received:
    6
    Reading List:
    Link
    Avoid naming your variables 'n', 'g', 'b'...

    You don't have to put all your variables at the beginning of the function.

    There is a boolean type for true/false, don't use an int to 0/1...

    Anyway, I found a real problem in the code :D

    Code:
    sorted[n][b] = str[i];
    
    Basically you have a std::string of 0 length, and you're modifying characters at position 0, 1, 2, 3... without increasing its size or allocating memory. If you did:

    Code:
    sorted[n].at(b) = str[i];
    
    You'd have an exception.

    If you want to push a character to make a string longer, you need to either:

    - use string.append()
    - create a new string, with the appropriate length, and edit it manually.

    As it is, you're basically accessing unallocated memory.
     
    Zaart likes this.
  13. Shtirliz

    Shtirliz Well-Known Member

    Joined:
    Feb 20, 2018
    Messages:
    179
    Likes Received:
    170
    Reading List:
    Link
    Are you sure that std::string will add space for your chars for you?
     
    Zaart likes this.
  14. chencking

    chencking [Daolord Grammar Nazi]

    Joined:
    Aug 1, 2016
    Messages:
    6,075
    Likes Received:
    4,160
    Reading List:
    Link
    '\0' is the null character, which terminates arrays
    Your issue is you are conflating allocating memory with initialization. Every vector must both be allocated and initialized. I am putting a more specific breakdown of your errors in the spoiler tag, but if you want to learn more from the exercise I recommend figuring it out yourself.

    1. You initialize the size of the sorted vector (allocation), but you do not initialize any of the strings.
    2. You pass into sorted pointers to str.
    3. You try to set unallocated chars.

    Your strings are each likely considered 0 length vectors, so you get undefined behavior. You should try using the std::vector intrinsics.

    PS: If you tried printing each character of sorted one by one, you would see each string in sorted points to yip. I hypothesize it is the yip in str at that. Do you see why that would likely be a result of some of your errors?

    PS: I saw you said you debugged your code. I took the time to run your code with an online compiler, and from my results you debugged incorrectly.
     
    Zaart likes this.
  15. Zaart

    Zaart Deer Master Race

    Joined:
    Oct 15, 2016
    Messages:
    1,320
    Likes Received:
    2,011
    Reading List:
    Link
    ooooh~
    thanks for the details!
    i think i kinda see what you mean
    the thing that confused me was that if i printed the character there was no problem but if i tried to display the string it didn't work
    i though i didn't have to initialise each string and indeed when i tried with printf i had random character
    so when i try to see the char it show me what was at the pointer of the char but the pointer of the string point to somewhere else?
    i though that like in c i could do something like pointer arithmetics and go to the next case by adding sizeof(char) (or the c++ equivalent) to a random case
     
  16. Zaart

    Zaart Deer Master Race

    Joined:
    Oct 15, 2016
    Messages:
    1,320
    Likes Received:
    2,011
    Reading List:
    Link
    that was so dumb of me when i think about it Q-Q
    i must lack sleep ^^ or food, or whatever else a human need to survive =P
    thanks ^^
     
  17. xiazixin

    xiazixin Well-Known Member

    Joined:
    Dec 7, 2017
    Messages:
    1,386
    Likes Received:
    657
    Reading List:
    Link
    C艹
    [​IMG]
     
    Zaart likes this.
  18. chencking

    chencking [Daolord Grammar Nazi]

    Joined:
    Aug 1, 2016
    Messages:
    6,075
    Likes Received:
    4,160
    Reading List:
    Link
    In C, I think you would have segfaulted. The C++ std::vector class seems to be a wrapper with an innate size parameter, much like ArrayLists in Java. If you used some type of std::vector access method, I bet they would have thrown an error. However, since you brute-forced it with C indexing it let you alter random pieces of data. Of course, the error revealed itself anyways when you tried to print. This is why we unit test when we program. There will always be errors. However a good programmer knows how to catch them.
     
    Zaart likes this.
  19. Zaart

    Zaart Deer Master Race

    Joined:
    Oct 15, 2016
    Messages:
    1,320
    Likes Received:
    2,011
    Reading List:
    Link
    Thanks man ^^
    Clear like water and just as useful