如何在 Main 方法之外将字符串拆分为标记

how to split string into tokens outside main method

本文关键字:拆分 字符串 Main 方法      更新时间:2023-10-16

我在堆栈溢出上看到了这段代码,

#include <sstream>
#include <iostream>
#include <vector>
using namespace std;
int main() {
    vector<string> strings;
    istringstream f("denmark sweden india us");
    string s;    
    while (getline(f, s, ' ')) {
        cout << s << endl;
        strings.push_back(s);
    }
}

但我似乎不明白为什么它在主方法之外不起作用。我有两个文件,一个是main方法,另一个是我想在其中实现此代码的文件。

这是我尝试过的

文件1.h

#include <iostream>
#include <iomanip> 
#include <string>
#include <string>
#include <sstream>
#include <vector>
#include <iterator>
using pep::vector;
using std::cout;
using std::endl;
using std::string;
double evaluate(string str)
{
    vector<string> strings;
    istringstream f(str);
    string s;    
    while (getline(f, s, ' ')) 
{
    out << s << endl;
    strings.push_back(s);
}
    return 0;
}

文件2.cpp

#include "file1.h"
int main() 
{
double answer = evaluate("3.0 4.0 +");
}

我收到这些错误:

file1.h: In function ‘double evaluate(std::__cxx11::string)’:
file1.h:89:5: error: ‘istringstream’ was not declared in this scope
     istringstream f(str);
     ^~~~~~~~~~~~~
file1.h:89:5: note: suggested alternative:
In file included from /usr/include/c++/6/ios:38:0,
                 from /usr/include/c++/6/ostream:38,
                 from /usr/include/c++/6/iostream:39,
                 from Stack.h:5:
/usr/include/c++/6/iosfwd:150:38: note:   ‘std::istringstream’
   typedef basic_istringstream<char>  istringstream;
                                      ^~~~~~~~~~~~~
file1.h:91:20: error: ‘f’ was not declared in this scope
     while (getline(f, s, ' '))
                    ^
file1.h:93:5: error: ‘out’ was not declared in this scope
     out << s << endl;

任何帮助将不胜感激

您提供的代码中有许多拼写错误。下次请确保您的代码在发布到此处之前经过拼写检查。

尝试将以下行更改为

using pep::vector; to  using std::vector;
istringstream f(str); to std::istringstream f(str);
out<<s<<endl; to  cout << s << endl;

改变这一点对我有用。

你提供的第一个例子,你有

using namespace std;

所以istringstream f(str);在没有范围运算符的情况下工作。