繁体   English   中英

来自 c++ 中下一个/新行的 ifstream

[英]ifstream from next/new line in c++

我将一组数据存储在一个基本上是名称的文件中。 我的任务是获取每个名字的所有首字母。 这是文件:

Jack fisher
goldi jones
Kane Williamson
Steaven Smith

我想从每行中取出第一个单词(例如,jack、goldi、kane、Steaven)我为它编写了以下代码,只是为了取出 2 个名字。 这里是:

    string first,last;
    ifstream Name_file("names.txt");
    Name_file>>first;
    Name_file>>endl;
    Name_file>>last;
    cout<<first<<" "<<last;

它给出了错误。 如果我删除 endl,它会采用第一个全名(Jack,fisher),而我希望它应该采用(jack,goldi)。 怎么做? 任何想法? 提前感谢您的帮助。

Name_file>>endl; 总是错的。

即使那样,您也不能像这样使用>> ,它会停在一个空格上,这就是为什么当您删除endl时,您会看到firstlast仅包含第一行的问题。

使用std::getline来遍历您的文件并获取全名,然后在第一个空格处拆分该行以获取名字:

ifstream Name_file("names.txt");

std::string line;
while (std::getline(Name_file, line))
{
  std::string firstName = line.substr(0, line.find(' '));
  //do stuff with firstName..
}

虽然我不介意“戴帽公鸡”的实现,但我认为当输入突然包含很长的行时,它的效率可能会降低一些。

我将使用ignore()删除该行的 rest:

int main()
{
    std::ifstream nameFile("names.txt");
    std::string firstName;

    while (nameFile >> firstName)
    {
        // You got a first name.
        // Now dump the remaing part of the line.
        nameFile.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }
}

我希望这能解决您的疑问。

ifstream Name_file;
string line;
Name_file.open("names.txt");
if(Name_file.fail()){ cerr<<"Error opening file names.txt !!"<<endl;return;}

vector<string> v; // array to store file names;

while(Name_file >> line){
    string word;
    getline(Name_file, word);
    v.push_back(line);
}

// printing the first names
for(int i = 0; i < v.size();i++){
    cout<<v[i]<<endl;
}

暂无
暂无

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

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