简体   繁体   English

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

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

I am having set of data stored in a file which are basically names.我将一组数据存储在一个基本上是名称的文件中。 My task is to get all the first letters from each name.我的任务是获取每个名字的所有首字母。 Here is the file:这是文件:

Jack fisher
goldi jones
Kane Williamson
Steaven Smith

I want to take out just first word from each line(ex. jack, goldi, kane, Steaven) I wrote following code for it, just to take take out 2 names.我想从每行中取出第一个单词(例如,jack、goldi、kane、Steaven)我为它编写了以下代码,只是为了取出 2 个名字。 Here it is:这里是:

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

it is giving error.它给出了错误。 If I remove endl, it takes the first full name(Jack, fisher) whereas I want it should take (jack,goldi).如果我删除 endl,它会采用第一个全名(Jack,fisher),而我希望它应该采用(jack,goldi)。 How to do it?怎么做? Any idea?任何想法? Thanks in advance for help.提前感谢您的帮助。

Name_file>>endl; is always wrong.总是错的。

Even then, you can't use >> like that, it will stop on a space, which is why when you remove endl you see the problem that first and last contain only the first line.即使那样,您也不能像这样使用>> ,它会停在一个空格上,这就是为什么当您删除endl时,您会看到firstlast仅包含第一行的问题。

Use std::getline to loop over your file instead and get the full names, then split the line on the first space to get the first name:使用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..
}

Though I don't mind "Hatted Rooster"implementation I think it can be a little less efficient when the input suddenly contains a very long line.虽然我不介意“戴帽公鸡”的实现,但我认为当输入突然包含很长的行时,它的效率可能会降低一些。

I would use ignore() to remove the rest of the line:我将使用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');
    }
}

I hope this solves your query.我希望这能解决您的疑问。

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