2012-10-17 82 views
0

感谢您对previous post的支持...我现在试图将矢量字符串存储在另一个字符串上,并执行sscanf来检查文本,例如。 “TEXT”,如果发现在行尾添加另一个文本....C++ sscanf读取字符串矢量

任何想法???

UPDATE: 我对sscanf的使用line.c_str(),并给出了此错误

#include <iostream> 
#include <vector> 
#include <string> 
#include <stdio.h> 

using namespace std; 

int main() { 
    vector<string> vs; 
    vector<string>::iterator vsi; 
    string agent; 
    string buffer; 
    string line; 
    while (!(cin.eof())) { 
    getline(cin, buffer); 
    cout << buffer << endl; 
    vs.push_back(buffer); 
    }; 

    vsi = vs.begin(); 
    for (int count=1; vsi != vs.end(); vsi++,count++){ 
    cout << "string" << count <<"="<< *vsi << endl; 
    line = *vsi; 
    cout << "LINE:" << line.c_str() << endl; 
    sscanf(line.c_str(), "%s %[^\n]",agent); 
/* cout << "agent" << agent << "endl"; */ 
    } 

    return 0; 
} 

[[email protected] dev]# g++ -o newcode newcode.cpp 
newcode.cpp: In function ‘int main()’: 
newcode.cpp:25: warning: cannot pass objects of non-POD type ‘struct std::string’ through ‘...’; call will abort at runtime 
[[email protected] dev]# 

我想要做的是当检测到特定线路上的字符串时,它会附加一个文本到行尾和标准输出...

+0

我看到你已经编辑了这个问题,你能否对发生错误的行号发表评论。像“\\这是25号线”这样的东西会非常有帮助。 – shuttle87

回答

1

这并不完全清楚你想要做什么,但如果你想获得正确的类型传入sscanf你需要改变一些东西。 sscanf只处理c字符串,并且您试图将它传递给C++字符串对象,要解决此问题,您可能需要在sscanf中使用line.c_str()以使其以正确的格式传递。

更好的方法是使用像string :: find这样的C++算法,因为这将消除使用sscanf的需要。

+0

感谢Shuttle87的回应,在使用line.c_str()时出错。 – krisdigitx

0

而不是使用sscanf尝试使用stringstream这工作几乎相同cin/cout的。