如何解决在C ++中拆分从文件读取的行
如何访问从文件读取的行的各个元素?
getline(infile,data) // where infile is an object of ifstream and data is the variable where the line will be stored
以下行存储在数据中:“快速的棕色狐狸跳过了懒狗”
我现在如何访问该行的特定元素?如果我想使用该行的第二个元素(quick)或抓住该行中的某个单词怎么办?如何选择?
任何帮助将不胜感激
解决方法
data = "The quick brown fox jumped over the lazy dog"
且数据为string,您的字符串分隔符为" "
,您可以使用std::string::find()
查找字符串分隔符的位置,并使用std::string::substr()
获取令牌:
std::string data = "The quick brown fox jumped over the lazy dog";
std::string delimiter = " ";
std::string token = data.substr(0,data.find(delimiter)); // token is "the"
,
由于您的文本用空格分隔,因此可以使用std::istringstream
来分隔单词。
std::vector<std::string> words;
const std::string data = "The quick brown fox jumped over the lazy dog";
std::string w;
std::istringstream text_stream(data);
while (text_stream >> w)
{
words.push_back(w);
std::cout << w << "\n";
}
operator>>
会将字符读入字符串,直到找到空格为止。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。