开发者

Stringstream to string logic C++

开发者 https://www.devze.com 2023-01-26 22:32 出处:网络
header.h #incl开发者_运维百科ude <iostream> #include <vector> class CombatLine{ std::stringstream Line;

header.h

#incl开发者_运维百科ude <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.


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)
{
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消