使用stringstream提取自句话.
每个单词都添加了换行符,我看不出原因; 你能?谢谢你的帮助.基思:^)
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <algorithm>
int main() {
int wordCount(9);
std::vector<std::string> v(wordCount);
std::vector<std::string>::iterator it;
std::string tStr;
std::string myStr = "the quick fox jumped over the lazy brown dogs";
std::stringstream ss(myStr);
std::cout << "Sentence broken into vector:" << std::endl;
for (int i=0; i<wordCount; ++i) {
ss >> tStr;
v.push_back(tStr);
}
for (it=v.begin(); it != v.end(); ++it)
std::cout << *it << std::endl;
std::cout << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
编译,运行和输出.注意额外的换行符.
pickledEgg $ g++ …Run Code Online (Sandbox Code Playgroud) 谷歌搜索了一下这一个,但似乎无法找到一个明确的答案.
如何在以下示例中调用unscramble()方法?
谢谢.:^)
class Food {
public:
Food(string _t):type(_t);
virtual void eat() = 0;
private:
string type;
}
class Fruit : public Food {
public:
Fruit(string _t):Food(_t) {
virtual void eat() { // Yummy.. }
}
class Egg : public Food {
public:
Egg(string _t):Food(_t)};
virtual void eat() { // Delicious! };
void unscramble();
}
int main() {
Food *ptr[2];
ptr[0] = new Fruit("Apple");
ptr[1] = new Egg("Brown");
// Now, I want to call the unscramble() method on Egg.
// …Run Code Online (Sandbox Code Playgroud) 比方说,我们想声明三个整数,p,q,和r.最好的做法是将它们初始化为0.ç这样做是这样:
int p, q, r;
p = q = r = 0;
Run Code Online (Sandbox Code Playgroud)
在C++这样做的方式是
int p(0), q(0), r(0);
Run Code Online (Sandbox Code Playgroud)
在C中,事情是美好而紧张的; 0仅使用一次.相反,C++调用要求0重复三次 - 每个变量一次.有点冗长.
有没有更简洁的方法使用C++方法初始化变量,还是每个变量声明所需的初始值?
另外,将C风格的初始化与C++代码混合在一起有什么问题吗?谢谢:^)
编辑:修复了正确编译的代码.现在,声明和初始化变量需要两行,所以问题不是很好,但我会把它留给后人.希望有人帮助.
有什么理由我们需要无效功能吗?
出于与int main()标准相同的原因,为什么不简单地0从不需要返回值的函数返回?我看到使用int类型有三个直接的好处:
1.我们可以返回一个代码来指示函数状态; 通常,如果出现问题,我们可以返回非零错误代码.
2.我们可以在调试时输出函数的返回值
3.它是main()例程的标准; 就是,int main() {}.为什么不跟风呢?
是否有任何理由为什么我们宁愿void过int?
示例:对奶酪数组进行排序并通过引用返回的函数.
#include <iostream>
#include <string.h>
int sortArrayInt(string & _cheese[]) { // pun intended ;D
int errCode = 0;
try {
// ..sort cheese[] array
} catch(e) {
errCode = 1;
}
return errCode;
}
void sortArrayVoid(string & _cheese[]) {
// .. sort cheese[] array
// no return code to work with, doesn't follow int main() standard, and …Run Code Online (Sandbox Code Playgroud)