Reputation: 43
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;
}
Upvotes: 1
Views: 175
Reputation: 121971
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);
Upvotes: 1