gpt4 book ai didi

c++ - getline(param1,param2,param3) 在 C++、linux 中的用法

转载 作者:太空宇宙 更新时间:2023-11-04 03:49:40 24 4
gpt4 key购买 nike

...可能是这么简单的问题,但我要编写一个简单的 C++ 代码来使用分隔符解析字符串,我希望分隔符包含多个空格(实际上是一个或多个空格)。我的问题是,可以这样做吗?我的示例代码是:

#include <stdio.h>
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <stdlib.h>
#include <cstring>
#include <sstream>
using namespace std;

int main()
{

string str="HELLO THIS IS 888and777";

char buf[1000];
getline(buf, 1000);
string str(buf);

stringstream stream(buf);
string toStr;

getline(stream, toStr,' ');//here the delimiter is six spaces
string str1=tostr;

getline(stream, toStr,' ');//here the delimiter is two spaces
string str2=tostr;

getline(stream, toStr,' ');//here the delimiter is three spaces
string str3=tostr;

cout<<str1<<"\t"<<str2<<"\t"<<str3<<endl;
return 0;
}

但是,我不能使用多个字符的分隔符。有什么想法请。我收到以下错误:

error: invalid conversion from ‘void*’ to ‘char**’
error: cannot convert ‘std::string’ to ‘size_t*’ for argument ‘2’ to ‘__ssize_t getline(char**, size_t*, FILE*)’

最佳答案

std::getline() 使用的分隔符纯粹是一个单独的字符。要接受字符串需要一个不平凡的算法来保证合适的性能。此外,使用 'x' 定义的实体通常需要生成单独的 char

对于这个例子,我认为最简单的方法是直接标记字符串:

#include <tuple>
#include <utility>
#include <string>
#include <iostream>

std::pair<std::string, std::string::size_type>
get_token(std::string const& value, std::string::size_type pos, std::string const& delimiter)
{
if (pos == value.npos) {
return std::make_pair(std::string(), pos);
}
std::string::size_type end(value.find(delimiter, pos));
return end == value.npos
? std::make_pair(value.substr(pos), end)
: std::make_pair(value.substr(pos, end - pos), end + delimiter.size());
}
int main()
{
std::string str("HELLO THIS IS 888and777");
std::string str1, str2, str3;
std::string::size_type pos(0);
std::tie(str1, pos) = get_token(str, pos, " ");
std::tie(str2, pos) = get_token(str, pos, " ");
std::tie(str3, pos) = get_token(str, pos, " ");

std::cout << "str1='" << str1 << "' str2='" << str2 << "' str3='" << str3 << "'\n";
}

关于c++ - getline(param1,param2,param3) 在 C++、linux 中的用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26783349/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com