2012-10-17 131 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的。