感谢你对previous post的支持……我现在正在尝试将向量字符串存储在另一个字符串上,并执行sscanf来检查文本,例如。" text“,如果找到,则在行尾追加另一个文本....
有什么想法吗?
#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;
sscanf(line, "%s %[^\n]",text);
//dummy code
if text=="TEXT" do this:
cout << "agent" << text << "endl";
}
else: do nothing
return 0;
}
[root@server dev]# g++ -o newcode newcode.cpp
newcode.cpp: In function ‘int main()’:
newcode.cpp:24: error: cannot convert ‘std::string’ to ‘const char*’ for argument ‘1’ to ‘int sscanf(const char*, const char*, ...)’
[root@server dev]# 更新:我在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;
}
[root@server 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
[root@server dev]# 我想要做的是,当检测到特定行上的字符串时,它会将文本附加到行尾和stdout……
发布于 2012-10-17 23:26:02
现在还不完全清楚你想要做什么,但是如果你想把正确的类型传递给sscanf,你需要改变一些东西。sscanf只处理c字符串,并且您尝试在c++字符串对象中传递它,为了解决这个问题,您可能希望在sscanf中使用line.c_str()来以正确的格式传递它。
更好的方法是使用像string::find这样的c++算法,因为这将消除使用sscanf的需要。
发布于 2012-10-17 23:29:19
我不确定您是否想这样做,但您应该查看string::find:Cplusplus reference
发布于 2012-10-17 23:29:43
不要使用sscanf,可以尝试使用stringstream,它的工作方式与cin/cout几乎相同。
https://stackoverflow.com/questions/12937690
复制相似问题