问题描述
如何访问从文件读取的行的各个元素?
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>>
会将字符读入字符串,直到找到空格为止。