Stringstream 到字符串逻辑 C++
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();
}
这个构建但我得到这个运行时错误, /cygdrive/C/Program Files/NetBeans 6.9.1/ide/bin/nativeexecution/dorun.sh: line 33: 4500 Segmentation failure
我知道这与我操作字符串的方式有关SetTokenFile 中的流,但我似乎无法确定是什么。
这是一个较大项目的一小部分。总的来说,我将解析一个动态文本文件,然后对整个文件的内容进行比较。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您无法直接写入
TokenLine[i]
,因为它在CombatLine
构造函数中被初始化为空vector
。如果您在阅读每一行时构建向量,则不需要调整大小
。试试这个:
或者,您可以在默认
CombatLine
构造函数的vector
中预分配 5 个条目,但如果您要处理的令牌数量发生变化,这会很脆弱。通过下面的代码,如果 0 <= i <= 4,您可以直接从stringstream
写入TokenLine[i]
。You cannot write directly into
TokenLine[i]
since it's initialized as an emptyvector
in yourCombatLine
constructor. You won't need theresize
if you build the vector up as you read each line.Try this:
Alternatively, you could preallocate 5 entries in the
vector
in the defaultCombatLine
constructor, though this is brittle if the number of tokens you want to process changes. With the below, you can write direct from thestringstream
intoTokenLine[i]
if 0 <= i <= 4.您需要先调整TokenLine的大小,然后写入内容,或者更好的习惯是使用push_back,它会在必要时调整大小。
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.