I am writing a program (just for "funziez") that takes multiple types of data in one line and stores it all in an array, for example if the user entered "agt bdafs ers 53 fv 2", i would use cin.getline(array,30) where array[] is a character array, and then use switch/if statements to check if a character is a number, where i would then convert it to an integer and store it somewhere else.
bottomline, i'm calling a function multiple times that uses cin.getline() as opposed to cin. the first time I call the function, cin.getline() works fine.
The second time it is called, it appears as though the cin.getline(); call gets ignored and the program procedes with bad results.
Any suggestions as to why this is occurring? When I use cin as opposed to cin.getline everything goes fine.
void GetInput();
int main()
{
for(int i = 2;i != 0;i--)
GetInput();
//unimportant code that does not relate to the GetInput function.
}
void GetInput()
{
char acInput[20];
cin.getline(acInput,20);
for(int iii = 0;acInput[iii] != '\0';iii++) //unimportant code that works with the acInput array assuming something is actually in it, which is the problem.
//more unimportant code.
}
the second time GetInput() is called, cin.getline(acInput,20); gets skipped and acInput is left empty. Is it because I don't have cin.clear() at the end? I'm not sure. thoughts?
The call to cin.getline( char* str, streamsize count ) will only read in count - 1 characters because it needs to affix the terminating '\0' character. In line 13:
cin.getline(acInput,20);
if you try to read a line with 20 or more characters only 19 characters will be read, the terminating '\0' affixed and the failbit set. Perhaps you are entering a 20 character line first time GetInput() is called causing the failbit to be set and subsequent calls to GetInput() to fail. I ran your code above and it worked fine if the entered lines had 19 or fewer characters, but truncated a line of 20 or more characters, setting the failbit and causing the second call to GetInput() to fail.