gpt4 book ai didi

c++ - 如何使用 getline() 终止

转载 作者:行者123 更新时间:2023-11-30 04:28:34 26 4
gpt4 key购买 nike

我正在尝试将一些整数存储在文件中,并使用“,”作为分隔符进行存储。现在,当我读取文件时,我使用 getline() 读取该行并使用 tokenizer 来分隔文件,但是,我无法终止该行,我需要 getline 中的一些 bool 条件来终止。

 while(getline(read,line)) {
std::cout<<line<<std::endl;
std::istringstream tokenizer(line);
std::string token;
int value;

while(????CONDN???) {
getline(tokenizer,token,',');
std::istringstream int_value(token);
int_value>>value;
std::cout<<value<<std::endl;
}
}

请指教。

最佳答案

在您的情况下,以与在外循环中相同的方式使用 getline 就足够了:

while(getline(tokenizer, token, ','))

虽然我很可能会这样做:

while(std::getline(read,line)) { // read line by line
std::replace(line.begin(), line.end(), ',', ' ' ); // get rid of commas
std::istringstream tokenizer(line);
int number;

while(tokenizer >> number) // read the ints
std::cout<<number<<std::endl;
}

还有另外两个替代方案 - 使用 Boost。

String Algorithms :

#include <boost/algorithm/string.hpp>
...
std::vector<std::string> strings;
boost::split(strings, "1,3,4,5,6,2", boost::is_any_of(","));

tokenizer :

#include <boost/tokenizer.hpp>
typedef boost::char_separator<char> separator_t;
typedef boost::tokenizer<separator_t> tokenizer_t;
...
tokenizer_t tokens(line, sep);
for(tokenizer_t::iterator it = tokens.begin(); it != tokens.end(); ++it)
std::cout << *it << std::endl;

如果您希望遇到非 int、非分隔符,例如1 3 2 XXXX 4。然后你必须决定在这种情况下该怎么做。 tokenizer >> number 将停止在不是 int 的地方,并且将设置 istringstream 错误标志。 boost::lexical_cast也是你的 friend :

#include <boost/lexical_cast.hpp>
...
try
{
int x = boost::lexical_cast<int>( "1a23" );
}
catch(const boost::bad_lexical_cast &)
{
std::cout << "Error: input string was not valid" << std::endl;
}

最后,在 C++11 中你有 stoi/stol/stoll功能:

#include <iostream>
#include <string>

int main()
{
std::string test = "1234";
std::cout << std::stoi(str) << std::endl;
}

关于c++ - 如何使用 getline() 终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10025972/

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