Friday, July 31, 2009

C ++ geline() does not ignore leading whitespaces. How do you overcome this problem?

the input data: 0 12123-13123\n


code: cin %26gt;%26gt; num;


getline(cin, numbers);





num is an int and numbers is a string.


but numbers= 12123-13123


there is a whitespace b4 1.





How do you get rid of it?





Thank you!

C ++ geline() does not ignore leading whitespaces. How do you overcome this problem?
The code is wrong. It's actually





"cin.getline(...,...);" AND NOT "getline(cin,...);"





And more I din't understand what you said. The only way to get rid of leading spaces (What do you mean by whitespaces?) is to run a loop checking this and if a space was given then to again accept string from user. So the modified program would be like this:





/* uGetline.cpp */


/* To understand the use of getline */


/* NOTE:- This program uses old Borland C++ Compiler */


/* Some statements have to be changed */


/* Read - Only */


/* By Senthil */





#include %26lt;iostream.h%26gt;


#include %26lt;conio.h%26gt;





char whtSp(char);


void main()


{


int num;


char numbers[150];


clrscr();





cout%26lt;%26lt;"Enter any number (within 32000) : ";


cin%26gt;%26gt;num;


cout%26lt;%26lt;"Enter anything : ";


numbers = whtSp();





do


{


cout%26lt;%26lt;"\nError! Please do not have a space in front!!!\n";


cout%26lt;%26lt;"Enter anything : ";


numbers = whtSp();


}while(numbers[0] != ' ')





clrscr();


cout%26lt;%26lt;"Value stored in int : "%26lt;%26lt;num;


cout%26lt;%26lt;"\nValue stored in char : "%26lt;%26lt;numbers;


getch();


}
Reply:none

liama-song

No comments:

Post a Comment