首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >c++ sscanf读取字符串向量

c++ sscanf读取字符串向量
EN

Stack Overflow用户
提问于 2012-10-17 23:20:53
回答 3查看 1.1K关注 0票数 0

感谢你对previous post的支持……我现在正在尝试将向量字符串存储在另一个字符串上,并执行sscanf来检查文本,例如。" text“,如果找到,则在行尾追加另一个文本....

有什么想法吗?

代码语言:javascript
复制
#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(),并给出了这个错误

代码语言:javascript
复制
#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……

EN

回答 3

Stack Overflow用户

发布于 2012-10-17 23:26:02

现在还不完全清楚你想要做什么,但是如果你想把正确的类型传递给sscanf,你需要改变一些东西。sscanf只处理c字符串,并且您尝试在c++字符串对象中传递它,为了解决这个问题,您可能希望在sscanf中使用line.c_str()来以正确的格式传递它。

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

票数 1
EN

Stack Overflow用户

发布于 2012-10-17 23:29:19

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

票数 0
EN

Stack Overflow用户

发布于 2012-10-17 23:29:43

不要使用sscanf,可以尝试使用stringstream,它的工作方式与cin/cout几乎相同。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12937690

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档