I have txt file and I need to read each word into char array. After reading, cout the word. So what I'm doing here is:
read char
while letter, add to array
when no letter, add '\0' in the end
What is wrong with my code?
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
char c;
char vaards[20];
int x;
fstream fin ("D:\\pilseta.txt", ios::in);
fin >> c;
while (fin)
{
if(isalpha(c));
{x=0;
vaards[x]=c;
x++;
fin >> c;
while(isalpha(c))
{
x++;
vaards[x]=c;
fin>>c;
}
x++;
vaards[x]='\0';
for (int i=0; vaards[i]!='\0'; i++)
cout<<vaards[i];
cout<<endl;
}
fin >> c;
}
fin.close();
system("pause");
return 0;
}
Problem 2: The entire thing, truley this is a mess don't salvage it, just start over. As a side note, the end of the array will be a '/0' anyway so you don't need to code that part.
- Your if(isalpha()) followed by while(isalpha()) is what we call redundent, don't do that.
- This is a loop, you should only have to tell fin to assign to c and increment x one time per iteration. On your reply post just do that without a loop and I'll tell you if it's right or not.
- Your for() loop to display the array is missing an '{'.
- You aren't counting the words anywhere in the code that I can see.