我正在编写代码来解析C++中的输入,但是无法修复这个错误。请帮助我调试它并解释代码,因为我是从某个地方复制的,不知道它遵循的逻辑。
#include<iostream>
#include<string>
#include<vector>
using namespace std;
int main()
{
string line = "GeeksForGeeks is a must try";
// Vector of string to save tokens
vector <string> tokens;
// stringstream class check1
stringstream check1(line);
string intermediate;
// Tokenizing w.r.t. space ' '
while(getline(check1, intermediate, ' '))
{
tokens.push_back(intermediate);
}
// Printing the token vector
for(int i = 0; i < tokens.size(); i++)
cout << tokens[i] << '\n';
}
最大的问题是缺少提供StringStream的#include
。之后,还有一个关于for循环的警告。它警告不要使用不同的整数类型进行比较。int
是带符号的,这意味着它是否定的。tokens.size()
返回一个size_t
,它是无符号的。整数行为可能会创建一些难以跟踪的bug,因此最好在可能的情况下避免混合使用有符号和无符号。如果您至少使用-wall-wextra
进行编译,您还会看到该警告。使用基于范围的for很容易克服该警告。
使用namespace std;
被认为是错误的做法。
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
int main() {
std::string line = "GeeksForGeeks is a must try";
// Vector of string to save tokens
std::vector<std::string> tokens;
std::stringstream check1(line);
std::string intermediate;
// Tokenizing w.r.t. space ' '
while (std::getline(check1, intermediate, ' ')) {
tokens.push_back(intermediate);
}
// Printing the token vector
for (auto i : tokens) {
std::cout << i << '\n';
}
}
这段代码工作的主要原因是std::StringStream
。流自然在空格上中断。因此,当我们向std::StringStream
提供对象line
时,它能够自动解析单词。这些字被放入std::vector
、令牌
中。std::vector
是分配在堆上的数组,可以在需要时增长。
就学习C++而言,互联网实际上并不是一个很好的资源,就像这个不完整的例子所展示的那样。我建议你买一本好书。