0

header.h

#include <iostream>
#include <vector>

class CombatLine{   
    std::stringstream Line;    
    std::vector<std::string> TokenLine;  
    void SetLine(std::string s){   
        Line<<s;   
    }    
public:   
void SetTokenLine(){   
    int i=0;    
    while(i<5){   
        Line>>TokenLine[i];   
        i++;}      
    TokenLine.resize(i);   
    for(int j=0;j<5;j++)   
        cout<<TokenLine[j];} 

main.cpp

#include "Header.h"
using namespace std;   

int main () {   
    CombatLine Line1;   
    Line1.SetLine("[Combat] A bird attacks -Anthrax- and misses (dodge).");   
    Line1.SetTokenLine();   
}   

This builds but I get this runtime error, /cygdrive/C/Program Files/NetBeans 6.9.1/ide/bin/nativeexecution/dorun.sh: line 33: 4500 Segmentation fault <core dumped> sh "$<SHFILE>"

I know it has to do with how I am manipulating strings & streams in the SetTokenFile, but I can't seem to pinpoint what.

This is a small piece to a larger project. Overall I am going to parse a dynamic text file, and later do comparisons on the entire file's contents.

1
  • 2
    Please use markdown codeblocks instead of HTML when formatting code; otherwise things like every < in your code block get removed (not to mention invalid HTML is generated). (Also, using namespace std; needs to die a horrendous death) Commented Nov 26, 2010 at 20:35

2 Answers 2

5

You cannot write directly into TokenLine[i] since it's initialized as an empty vector in your CombatLine constructor. You won't need the resize if you build the vector up as you read each line.

Try this:

void SetTokenLine(){   
    int i=0;    
    string nextLine;
    while(i<5){   
        Line>>nextLine;
        TokenLine.push_back(nextLine);
        i++;}      
    for(int j=0;j<5;j++)   
        cout<<TokenLine[j];}

Alternatively, you could preallocate 5 entries in the vector in the default CombatLine constructor, though this is brittle if the number of tokens you want to process changes. With the below, you can write direct from the stringstream into TokenLine[i] if 0 <= i <= 4.

CombatLine::CombatLine() : TokenLine(5)
{
}
Sign up to request clarification or add additional context in comments.

Comments

1

You need to resize TokenLine first, and THEN write into the contents, or a better habit is to use push_back, which will resize if necessary.

Comments

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.