0

前の投稿のサポートに感謝します...私は今、ベクター文字列を別の文字列に保存し、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]# 

私がやりたいのは、特定の行の文字列が検出されたときに、行末と標準出力にテキストを追加することです...

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を使用する代わりに。stringstreamcincout

于 2012-10-17T15:29:43.100 に答える