我是一名新程序员(< 1 年),所以如果我把简单的事情弄复杂了,请原谅。
我正在尝试删除给定字符串中的所有空格(制表符和空格字符),并将数据作为单个元素存储在向量中。我还想考虑前导和尾随空白。
我尝试使用字符串方法在字符串中向前移动两个索引,同时检查这些字符。到目前为止,我已经至少重写了五次代码,但我总是得到:
terminate called after throwing an instance of 'std::out_of_range'
what(): basic_string::at: __n (which is 7754) >= this->size() (which is 42)
Aborted (core dumped)
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void makeTokens(string& separate);
int main()
{
string test = " u 65.45\t\t 36.12\t 78.25 0.00";
makeTokens(test);
return 0;
}
void makeTokens(string& separate)
{
vector<string> tokens;
unsigned short index1, index2 = 0;
while (separate.at(index1) == ' ' || separate.at(index1) == '\t')
{
index1++;
index2 = index1 + 1;
}
while (index2 < separate.length())
{
if (separate.at(index2) == ' ' || separate.at(index2) == '\t')
{
tokens.push_back(separate.substr(index1, index2 - index1));
index1 = index2;
while (separate.at(index1) == ' ' || separate.at(index1) == '\t')
{
index1++;
}
index2 = index1 + 1;
}
else
{
index2++;
}
if (index2 == separate.length() - 1)
{
if (separate.at(index2) == ' ' || separate.at(index2) == '\t')
{
tokens.push_back(separate.substr(index1));
}
}
}
for (unsigned short i = 0; i < tokens.size(); i++)
{
cout << tokens[i] << "|" << endl;
}
}
我希望控制台输出:
u|
65.45|
36.12|
78.25|
0.00|
如果通过了类似的测试字符串,除了末尾有空格,我仍然想要相同的输出。
编辑:我已将索引声明更改为:
unsigned short index1 = 0;
unsigned short index2 = 0;
现在控制台输出:
u|
65.45|
36.12|
78.25|
最后的 0.00 仍然缺失。
这很容易通过使用std::istringstream
:
#include <string>
#include <sstream>
#include <iostream>
#include <vector>
int main()
{
std::string test = " u 65.45\t\t 36.12\t 78.25 0.00";
std::istringstream strm(test);
std::string word;
std::vector<std::string> words;
while (strm >> word)
words.push_back(word);
for (auto& v : words)
std::cout << v << "|\n";
}
输出:
u|
65.45|
36.12|
78.25|
0.00|
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句