By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
434,587 Members | 1,101 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 434,587 IT Pros & Developers. It's quick & easy.

how to detect end of line \n c++ urgent

P: 11
hiii
i am trying to read a file which has data in the form of an array .. to count the number of lines i need to count number of \n ... but i m unable to do so ..
char ch;
while(infile>>ch)
{

if(ch=='\n')
cout<<" end ";
else
cout<<" cont. ";

c++;
}
infile.close();
cout<<" c="<<c;
it does not detect \n ...
please help .
i am pretty new to c++.... please reply as soon as poss.. :)
Jun 15 '07 #1
Share this Question
Share on Google+
5 Replies


Savage
Expert 100+
P: 1,764
hiii
i am trying to read a file which has data in the form of an array .. to count the number of lines i need to count number of \n ... but i m unable to do so ..
char ch;
while(infile>>ch)
{

if(ch=='\n')
cout<<" end ";
else
cout<<" cont. ";

c++;
}
infile.close();
cout<<" c="<<c;
it does not detect \n ...
please help .
i am pretty new to c++.... please reply as soon as poss.. :)
That's because of >> operator.This operator breakes extraction from file when it encounters whitespace,use getline instead..

Savage
Jun 15 '07 #2

P: 11
That's because of >> operator.This operator breakes extraction from file when it encounters whitespace,use getline instead..

Savage
can i get the characters without the spaces .. ?? into an array ..??
Jun 15 '07 #3

P: 11
can i get the characters without the spaces .. ?? into an array ..??
i am reading the array once using getline .. to get no. of lines . .. then again the total number of characters ( by >>)... then i divide the two to get no. of columns.. then i am reading al the characters in the file into an array using >> .. each time i have to use a differnt stream , otherwise there is failure in opening the file ..
is dere a simpler way out..???
Jun 15 '07 #4

P: 9
You will need two streams to read and write to the file, if memory serves correctly. However, you could use a string to store every line you read using getline and then use a length function to find the length of the string (# of characters). That eliminates one stream. Hope that helps.
Jun 15 '07 #5

weaknessforcats
Expert Mod 5K+
P: 9,197
You may be making this too hard.

1) the file has the strings
2) you need to read the stirngs into an array
3) this is C++. The array is implemented by vector
Ergo: read the strings into a vector.

Expand|Select|Wrap|Line Numbers
  1. ifstream input("data.txt");
  2. char buffer[256];
  3. string str;
  4. vector<string> array;
  5. while (!input.eof())
  6. {
  7.     input.getline(buffer, 256);        
  8.     str = buffer;
  9.     array.push_back(str);
  10. }
  11.  
Jun 15 '07 #6

Post your reply

Sign in to post your reply or Sign up for a free account.