C++ 用零来划分单词是不正确的
最近,我一直在为期末考试写片段。常见任务之一是将字符串(std::string)划分为单词。在某些情况下,这些字符串可以包含整数 我写了一段话:C++ 用零来划分单词是不正确的,c++,string,istringstream,C++,String,Istringstream,最近,我一直在为期末考试写片段。常见任务之一是将字符串(std::string)划分为单词。在某些情况下,这些字符串可以包含整数 我写了一段话: #include <sstream> #include <iostream> #include <vector> using namespace std; int main(void) { string str="23 005 123"; vector<int>myints; istringstream
#include <sstream>
#include <iostream>
#include <vector>
using namespace std;
int main(void)
{
string str="23 005 123";
vector<int>myints;
istringstream iss(str);
string word;
while(iss>>word)
{
int a;
istringstream(word)>>a;
myints.push_back(a);
}
for (vector<int>::iterator it=myints.begin();it!=myints.end();++it)
cout<<*it<<" ";
}
#包括
#包括
#包括
使用名称空间std;
内部主(空)
{
字符串str=“23 005 123”;
向量;
istringstream iss(str);
字符串字;
while(iss>>word)
{
INTA;
istringstream(word)>>a;
myints.向后推(a);
}
for(vector::iterator it=myints.begin();it!=myints.end();++it)
cout如果您需要记住输入的前导零数,并在以后使用完全相同的前导零数打印它,唯一的选择是不存储为int
。例如,您可以将向量
转换为向量
或者,您可以使用向量
,它将所需的整数与原始字符串表示形式一起保留
最后,如果您不关心输入中前导零的实际数量,而只是希望用前导零填充所有内容使其长度相等,则可以使用setfill
和setw
:
cout << setfill('0') << setw(5) << 25;
cout