繁体   English   中英

拆分从 C++ 中的文件读取的一行

[英]Split a line read from a file in 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" and the data is 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来分隔words

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>>将字符读入字符串直到找到空格。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM