0

I am an absolute beginner to c++ and for assignment I need to do multiple functions and send the single .cpp file.

My code is:

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<string>
using namespace std;

char* toTitleCase(const char* text) {
    int i;
    char a[30];
    cin.getline(a, 30);   
    a[0] = a[0] - 32;        

    for (i = 0; a[i] != NULL; i++)
    {
        if (a[i] == ' ')
        {
            a[i + 1] = a[i + 1] - 32;
        }
    }

    cout << a;
    return 0;

    } 
char* removeSpaces(const char* text) {
    char str[100];
    int i = 0, len, j;
    cout << "Enter a string: ";
    gets_s(str);
    len = strlen(str);
    for (i = 0; i < len; i++) {
        if (str[i] == ' ') {
            for (j = i; j < len; j++)
                str[j] = str[j + 1];
            len--;
        }
    }
    cout << "Result string: " << str;
    return 0;
}

int main() {
    cout << removeSpaces("hello. this is a test");

    cout << toTitleCase("hello. this is a test");
    char str[100];
    //cout << "Result string: " << removeSpaces(str);
  
    return 0;
}

The problem is that, it only works for the first called function but not the second, and it just exits the code. Please, any reason why or what would I be supposed to do?

ChrisMM
  • 8,448
  • 13
  • 29
  • 48
  • I don't understand your question ... you are calling two functions from `main` as it is. You are not printing anything useful from `main` though. – ChrisMM Nov 02 '22 at 17:58
  • In both functions you promise to return a `char*` and then `return 0`; which is legal; BUT then the code in `main` tries to use the returned value (`0`) as a `char*` to output the c-string (via `cout << `) which is not legal. – Richard Critten Nov 02 '22 at 17:59
  • Your function returns `0` while the return type is `char*` and then use `cout<<` with that returned pointer which will lead to undefined behavior. – Jason Nov 02 '22 at 18:02
  • just change return type to `std::string` and return from function something meaningful (not `0`). Now your code is invalid (has undefined behavior). It ends execution since there is a crash. – Marek R Nov 02 '22 at 18:02
  • When I return "a" and "str" instead of 0 when compiling it just prints random hexa values – Catalin-Gabriel Nov 02 '22 at 18:06
  • This is wrong to. Just do what I've told you. – Marek R Nov 02 '22 at 18:07
  • And do not do Input Output operations inside of `toTitleCase` `removeSpaces`. Those functions should accept `std::string` and return `std::string`. – Marek R Nov 02 '22 at 18:08
  • You can start over from this: https://godbolt.org/z/G8Gq6Tzq9 – Marek R Nov 02 '22 at 18:15

0 Answers0