如何在 Main 方法之外将字符串拆分为标记
how to split string into tokens outside main method
我在堆栈溢出上看到了这段代码,
#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);
在没有范围运算符的情况下工作。
相关文章:
- 我还可以添加什么来按空格或空格正确拆分C++字符串?
- 通过空行提升拆分字符串
- 如何按多个括号类型拆分字符串,但仍将括号保留在C++?
- 如何根据字符拆分字符串
- 在C++中拆分字符串的最佳做法
- 如何使用两个不同的分隔符拆分字符串
- 基于 C++ 中的多个字符串分隔符拆分字符串
- 拆分字符串输入并查找字符是否有效
- 使用 boost::split 按分隔符的前 N 次匹配来拆分字符串
- 如何在C 中不带有弦乐和strtok的情况下拆分字符串(提取单词)
- 为什么在黑客兰克的许多问题中都会完成拆分字符串
- C++拆分字符串反馈
- C++:按制表符拆分字符串,但包含空格
- 基于其中的数字子字符串拆分字符串
- 按空格拆分字符串并将列输出到不同的数组中
- C++ STL 在逗号处拆分字符串
- 如何根据某些字符拆分字符串?经度纬度
- 如何在 c++ 中拆分字符串的一部分
- 如何通过分隔符拆分字符串并将每个字符串放入不同的向量中
- 我如何在QT中的更多子字中拆分字符串