Arjun dev Mishra
Arjun dev Mishra

Reputation: 29

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. 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). How to do it ? Any idea? Thanks in advance for help.

Upvotes: 0

Views: 292

Answers (3)

Loki Astari
Loki Astari

Reputation: 264381

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:

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');
    }
}

Upvotes: 2

risingStark
risingStark

Reputation: 1155

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;
}

Upvotes: 0

Hatted Rooster
Hatted Rooster

Reputation: 36463

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.

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:

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..
}

Upvotes: 2

Related Questions