用C++标记字符串

Cod*_*key 6 c++

我有一个字符串currentLine ="12 23 45"

我需要从这个字符串中提取12,23,45而不使用Boost库.由于我使用字符串,strtok对我失败了.我尝试了很多事情仍然没有成功.

这是我的最后一次尝试

while(!inputFile.eof())
    while(getline(inputFile,currentLine))
        {
            int countVar=0;
            int inputArray[10];
            char* tokStr;
            tokStr=(char*)strtok(currentLine.c_str()," ");

            while(tokstr!=NULL)
            {
            inputArray[countVar]=(int)tokstr;
            countVar++;
            tokstr=strtok(NULL," ");
            }
        }
}
Run Code Online (Sandbox Code Playgroud)

没有strtok的人

string currentLine;
while(!inputFile.eof())
    while(getline(inputFile,currentLine))
        {
            cout<<atoi(currentLine.c_str())<<" "<<endl;
            int b=0,c=0;
            for(int i=1;i<currentLine.length();i++)
                {
                    bool lockOpen=false;
                    if((currentLine[i]==' ') && (lockOpen==false))
                        {
                        b=i;
                        lockOpen=true;
                        continue;
                        }
                    if((currentLine[i]==' ') && (lockOpen==true))
                        {
                        c=i;
                        break;
                        }
                }
            cout<<b<<"b is"<<" "<<c;    
        }
Run Code Online (Sandbox Code Playgroud)

k06*_*06a 9

试试这个:

#include <sstream>

std::string str = "12 34 56";
int a,b,c;

std::istringstream stream(str);
stream >> a >> b >> c;
Run Code Online (Sandbox Code Playgroud)

在这里阅读很多关于c ++流的内容:http://www.cplusplus.com/reference/iostream/


Kon*_*lph 5

std::istringstream istr(your_string);

std::vector<int> numbers;
int number;
while (istr >> number)
    numbers.push_back(number);
Run Code Online (Sandbox Code Playgroud)

或者,更简单(虽然不是很短):

std::vector<int> numbers;
std::copy(
    std::istream_iterator<int>(istr),
    std::istream_iterator<int>(),
    std::back_inserter(numbers));
Run Code Online (Sandbox Code Playgroud)

(需要标准标题<sstream>,<algorithm>和<iterator>.)