1

I want to take in user input and put what they type into an array of strings. I want it to read each character and separate each word by white space. I am sure this is coded badly, although I did try to do it decent. I am getting a segmentation fault error and was wondering how I could go about doing this without getting the error. Here is the code I have.

#include <iostream>

using namespace std;

void stuff(char command[][5])
{ 
    int b, i = 0;
    char ch;
    cin.get(ch);

    while (ch != '\n')
    {
        command[i][b] = ch;
        i++;
        cin.get(ch);
        if(isspace(ch))
        {
            cin.get(ch);
            b++;

        }

    }
    for(int n = 0; n<i; n++)
    {
        for(int m = 0; m<b; m++)
            {
            cout << command[n][m];
            }
    }

}

int main()
{
    char cha[25][5];
    char ch;
    cin.get(ch);
    while (ch != 'q')
    {
        stuff(cha);
    }

    return 0;
}
1
  • Why not using a std::vector<std::string> > and apply cin to the strings? Commented Dec 9, 2012 at 9:15

1 Answer 1

1

b is not initialised so will have a random value when first used as the index. Initialise b and ensure array indexes do not go beyond the bounds of the array.

Alternatively, use a std::vector<std::string> and operator>>() and forget about array indexes:

std::string word;
std::vector<std::string> words;
while (cin >> word && word != "q") words.push_back(word);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Whenever I use a space I get weird characters in the array. Do you know what would fix that also?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.