0

感谢对上一篇文章的支持......我现在正在尝试将矢量字符串存储在另一个字符串上并执行 sscanf 来检查文本,例如。“文本”,如果找到,则在行尾附加另一个文本....

有任何想法吗???

#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]# 

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

4

3 回答 3

1

目前尚不清楚您要做什么,但是如果您想将正确的类型传递给 sscanf ,则需要进行一些更改。sscanf仅处理 c 字符串,并且您尝试将其传递给 c++ 字符串对象,要解决此问题,您可能希望line.c_str()在 sscanf 中使用以正确格式传递它。

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

于 2012-10-17T15:26:02.333 回答
0

我不确定您是否想这样做,但您应该查看 string::find : Cplusplus 参考

于 2012-10-17T15:29:19.227 回答
0

而不是使用sscanftry using stringstreamwhich 工作几乎与cin/相同cout

于 2012-10-17T15:29:43.100 回答