#include<iostream>
#include<fstream>
#include <sstream>
#include<string>
using namespace std;

void main()
{
    std::ifstream fin("romanian.txt");
    std::ofstream fout("output.txt");
    std::string line;

    int i;
    int count=0;
    string word;

    while(!fin.eof())
    {
        getline(fin,line);

        for(i=0;i<line.length();i++)
        {
            if(line[i]==' ')
            {
                break;
            }
            cout<<line;
        }



    }
    system("PAUSE");
}

the prog get crashed ... can any one please give me help how to read first line from file the file is in format:
abc def
gef hij
sss fff
sdsdd fvf

output should be
abc
gef
sss
sdsdd
please i need help learning file handlng nw

Recommended Answers

All 3 Replies

line 23 is looking for the end of the first word, but then you display the entire line on line 27. before the break on line 25 you need to truncate the string at the end of the first word. First call std::string's find() method to get the position of the first space, then call std::string's substr() method to extract just the first word.

#include<iostream>
#include<fstream>
#include <sstream>
#include<string>
using namespace std;

void main()
{
    std::ifstream fin("romanian.txt");
    std::ofstream fout("output.txt");
    std::string line;
    stringstream ss;

    int i;
    int count=0;
    string temp,word;
    int sp;

    while(std::getline(fin,line))
    {
        for(i=0;i<line.length();i++)
        {
            line.substr(0,'32');


        }
        cout<<line<<endl;

    }
    fin.close();

    system("PAUSE");
}

still not working :(

Change

while(std::getline(fin,line))
{
    for(i=0;i<line.length();i++)
    {
        line.substr(0,'32');


    }
    cout<<line<<endl;

}

To

while(std::getline(fin,line))
    cout << line.substr(0, line.find_first_of(" ", 0)) << endl
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.