strange error
May 16, 2008 at 3:07pm UTC
i cant, for the life of me, figure out what is wrong with this program. i get a segmentation error. i can't assign any value to userInput. why? instead of using getline(), ive even tried using something as simple as
userInput = "hello" ;
except it still spits out a segmentation error. here is the code. someone please help
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
#include <iostream>
#include <string>
#include <vector>
#include <cctype>
using namespace std;
int main(void )
{
vector<string> words;
int y = 0;
int i = 0;
int j = 0;
string userInput;
cout << "Enter your statement: " ;
getline(cin, userInput);
cout << userInput;
int size = userInput.size();
for (; i < size; i++)
{
while (isspace(userInput[i]) == true )
{
continue ;
}
j = i;
while (isspace(userInput[j]) == false )
{
j++;
}
words.push_back(userInput.substr(i, j - i));
y++;
i = j;
}
for (unsigned int x = 0; x < words.size(); x++)
{
cout << words[x] << endl;
}
return 0;
}
May 16, 2008 at 3:39pm UTC
is this always true (i < size) ?
(hint: try running your program an typing in a string that ends with a space.)
A cleaner way would be to use a stringstream:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
int main() // no void: this is C++, not C99
{
vector<string> words;
string userInput;
cout << "Enter your statement: " ;
getline(cin, userInput);
cout << '\"' << userInput << '\"' << endl;
{
stringstream ss( userInput );
string s;
while (getline( ss, s, ' ' ))
words.push_back( s );
}
for (int i = 0; i < words.size(); i++)
cout << words[ i ] << endl;
return EXIT_SUCCESS;
}
May 16, 2008 at 3:58pm UTC
May be due to the below lines code
1 2 3 4
while (isspace(userInput[j]) == false )
{
j++;
}
"j" goes on increasing iff Ur last character is not a space one...
Check the value of j again size may help u.
1 2 3 4 5 6 7
while (isspace(userInput[j]) == false )
{
j++;
if (j>=size)
break ;
}
May 16, 2008 at 8:46pm UTC
This bit looks like an infinite loop as well if the string starts with a space
1 2 3 4
while (isspace(userInput[i]) == true )
{
continue ;
}
Topic archived. No new replies allowed.