Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ segmentation fault in function

Learning some basic C++, trying to understand functions but having a hell of a time trying to properly write the function. Here's the original code (works fine):

#include <iostream>
#include <string>
//#include "assn.h"

using namespace std;

int main()
{
    string userinput;
    char ch1 = '-';

    cout << "Enter word: ";
    getline(cin, userinput);

    int i = 0;
    for (i; i < userinput.size(); ++i)
    {
        if (userinput.at(i) >= 'a' && userinput.at(i) <= 'z')
        userinput.at(i) = ch1;
    }

    cout << userinput << endl;
    return 0;
}

and here's the code I typed trying to make it a function:

#include <iostream>
#include <string>
//#include "assn.h"

using namespace std;

string inputUnsolved(string input);

int main()
{
        string userinput;
        cout << "Enter word: ";
        getline(cin, userinput);

        inputUnsolved(userinput);

        cout << userinput << endl;
        return 0;
}

string inputUnsolved(string input)
{
    char ch1 = '-';

    int i = 0;
    for (i; i < input.size(); ++i)
    {
        if (input.at(i) >= 'a' && input.at(i) <= 'z')
            input.at(i) = ch1;
    }
}

It compiles fine, but after entering the userinput and trying to execute, it displays "Segmentation fault"

Tried rewriting a few times with no luck and I quite honestly don't know enough to find a way to fix it. The code basically reads in a string variable and displays it as a set of dashes (hangman).

like image 299
HHughes Avatar asked Feb 03 '26 13:02

HHughes


1 Answers

Pass by reference instead

void inputUnsolved(string& input);
like image 141
Digital_Reality Avatar answered Feb 05 '26 02:02

Digital_Reality



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!