【发布时间】:2016-11-01 18:26:02
【问题描述】:
我有以下字符串:
1 -2 -8 4 51
我想得到一个包含 5 个元素的向量,每个元素对应于字符串中的 5 个数字。基本上,我想用空格分割上面的字符串作为分隔符。
我在 Stack Overflow 上发现了很多这样的问题,但到目前为止,他们中的任何一个都无法得到第一个“1”或最后一个(来自51)。
我的代码如下:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <sstream>
using namespace std;
std::vector<std::string> split(std::string str)
{
std::string buf;
std::stringstream ss(str);
vector<std::string> tokens;
while (ss >> buf)
tokens.push_back(buf);
return tokens;
}
int main()
{
std::string temps = "1 -2 -8 4 51";
std::vector<std::string> x = split(temps);
for (int j = 0; j < x.size(); j++){
cout << x[j] << endl;
}
}
我的输出如下:
-2
-8
4
5
如您所见,第一个和最后一个 1 被跳过。
我对 C++ 很陌生(我可能已经习惯了其他语言的内置函数 .split()),但我在上面的代码中看不到任何错误。
谁能帮我理解我做错了什么?
【问题讨论】:
-
err 在这里工作正常。我按预期得到
1 -2 -8 4 51... -
你的编译器是什么?在 gcc 上运行良好:melpon.org/wandbox/permlink/RZOT5kbvHvPraz5b
-
也许这是一个很大的问题,但是:在程序的开头打印一个换行符。也许你只是监督第一个。另一个问题:您可能会从 x.size 返回与 int 不同的类型。尝试将 x.size() 转换为 int
-
我在coding challenge website 上练习,但如果你们无法重现,我猜这是他们编译器的问题,所以我要关闭这个帖子。对此感到抱歉。