0

//i am writing a code that read from a file and store words in an character array but //in the wriiten by me,it is compiling but not extracting words in the array.

#include<iostream>
#include<fstream>
#include<string>
#include<string.h>
using namespace std;

int main()
{
ifstream fin;
char ch;
int j=0;
string line;


//reading from file.....
fin.open("rajkamal");//rajkamal is a valid file.
while(fin)
{
getline(fin,line);
}
cout<<"\n"<<line;
fin.close();

//putting data into an array from a string.
cout<<"\n"<<line;
char *a=&line[0];
cout<<endl;
cout<<a<<"******"<<endl;
cout<<a[0]<<a[1]<<a[2]<<a[3]<<endl;

int r=0,c1=0,i=0;
char word[10][10];
for(i=0;i<line.length();i++)
{
if(a[i]=' ')
{
word[r][c1++] = line[i];
}
else
{
word[r++][c1]=0;
c1=0;
}
}
word[r][c1]=0;


for(i=0;i<=r;i++)
{
cout<<word[i]<<"\n";
}

return 0;
}

Edited by Nick Evan: added code-tags

3
Contributors
3
Replies
4
Views
6 Years
Discussion Span
Last Post by Ancient Dragon
Featured Replies
  • That program is only processing the last line of the file, not the entire file's contents. Each time getline() is executed on line 18 it replaces the current contents of variable [b]line[b] with another string that is read from the file -- in otherwises getline() doesn't just tack the new … Read More

0

this code has worked .i had left "!"in a for loop .this is a good code that extract words from sentence and store it in a character array.

0

So the only thing you want is the last line of the file I assume... since your while() loop will not break until reaching the end of your file.

Edited by Duki: n/a

1

That program is only processing the last line of the file, not the entire file's contents. Each time getline() is executed on line 18 it replaces the current contents of variable line with another string that is read from the file -- in otherwises getline() doesn't just tack the new string to the end of the existing string's contents.

line 35: >> if(a=' ')
pointer a is completely unnecessary. You can index into std::string the same as char*.
Use the == boolean operator, not the = assignment operator
That if statement is 100% wrong anyway.


for(size_t i = 0; i < line.length(); i++)
    {
        words[r][c1] = line[i];
        if( line[i] == ' ' || (i+1) == line.length()) 
        {
            words[r][c1] = 0; // null terminate the word
            r++;              // advance to the next word
            c1 = 0;           // reset to beginning of new word
        }
        else
            c1++;
    }

And there are other ways to accomplish the same thing. The above is just one of them.

Edited by Ancient Dragon: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.